通过链接函数扩展构建器模式

时间:2015-09-14 04:30:29

标签: javascript promise builder

我已经将Brototype分叉并将其弄清楚,以便更具可读性。我正在尝试将一个额外的函数链接到构建器模式,但我迷失了从哪里开始。 (我尝试添加额外的Promise回调,但这不起作用)。

这是原始的(截断的)副本:

'use strict';

function Promise(object, method, args) {
    this.object = object;
    this.method = method;
    this.args = args.length > 1 ? args.slice(1) : [];
}

Promise.ok = Promise.prototype = {
    "do": function(callback, context) {
        if (this.method instanceof Function) {
            var returnValue = this.method.apply(this.object, this.args);
            if (returnValue) {
                (callback || function(){}).call(context || this.object, returnValue);
            }
        }
        return context;
    }
};

function Ok(obj) {
    if (this instanceof Ok) {
        this.obj = obj;
    } else {
        return new Ok(obj);
    }
}

Ok.true = true;
Ok.false = false;

Ok.ok = Ok.prototype = {
    "exists": function() {
        return this.obj !== void 0;
    },

    "ifExists": function(methodString) {
        var method = this.getIfExists(methodString);
        return new Promise(this.obj, method, arguments);
    }

};

module.exports = Ok;

我是如何使用它的:

ok(app)
    .ifExists('nested.property')
    .do(function(property){
        // something with property
    });

我希望能够做到:

ok(app)
    .ifExists('nested.property')
    .do(function(property){
        // something with property
    })
    .else(function() {
        // something else
    });

所以我尝试添加:

Promise.ok = Promise.prototype = {
    "do": function(callback, context) {
        if (this.method instanceof Function) {
            var returnValue = this.method.apply(this.object, this.args);
            if (returnValue) {
                (callback || function(){}).call(context || this.object, returnValue);
            }
        } else {
            return new Promise(this.obj, this.else, this.args);
        }
        return context;
    },
    "else": function(callback) {
        // I don't even know? Sigh
    }
};

0 个答案:

没有答案
相关问题