且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过原型将计算的observable添加到构造函数

更新时间:2023-11-30 23:24:58

我还在论坛中对此进行了回答

这是一种方法( jsFiddle示例 ):

<div data-bind="text: fullDomainName">test</div>
<script>
function SiteModel(rootUrl, data) {
    var self = this;
    self.rootUrl = rootUrl;
    self.DomainName = ko.observable(data.DomainName);
    self.IsSubDomain = ko.observable(data.IsSubDomain);
    self.fullDomainName = ko.computed(self.fullDomainName, self);
}

SiteModel.prototype.fullDomainName = function () {
    if (this.IsSubDomain() && this.DomainName()) { // bombs out here with "self.IsSubDomain is not a function"
        return this.DomainName() + ".myCompanyWebsite.com";
    }
    else {
        return this.DomainName();
   }
}; 

var temp = new SiteModel("someurl", { DomainName: "extraCool" });

ko.applyBindings(temp);
</script>

我已经在原型中定义了函数并使其成为一个计算的
observable构造函数。

I've defined the function in the prototype and made it a computed observable in the constructor.

这是一种更通用的方式( jsFiddle示例):

Here's a way to do it a more generic way (jsFiddle example):

<div data-bind="text: fullDomainName">test</div>
<script>
Function.prototype.computed = function() {
    this.isComputed = true;
    return this;
};
Object.prototype.makeComputeds = function() {
    for (var prop in this) {
        if (this[prop] && this[prop].isComputed) {
            this[prop] = ko.computed(this[prop], this, {deferEvaluation:true});
        }
    }
};

function SiteModel(rootUrl, data) {
    var self = this;
    self.rootUrl = rootUrl;
    self.DomainName = ko.observable(data.DomainName);
    self.IsSubDomain = ko.observable(data.IsSubDomain);
    self.makeComputeds();
}

SiteModel.prototype.fullDomainName = function () {
    if (this.IsSubDomain() && this.DomainName()) { // bombs out here with "self.IsSubDomain is not a function"
        return this.DomainName() + ".myCompanyWebsite.com";
    }
    else {
        return this.DomainName();
   }
}.computed();

var temp = new SiteModel("someurl", { DomainName: "extraCool" });

ko.applyBindings(temp);
</script>

计算的基础读取函数将通过原型$共享b $ b虽然实际的计算属性不会。我想如果你创建了一些对象然后改变了
原型中的函数,可能会产生
混乱。新对象将使用新函数,但旧对象
不会。

The underlying read function of the computed will be shared via the prototype although the actual computed property won't. I suppose there could be confusion if you created some objects and then changed the function in the prototype. New objects would use the new function, but old objects wouldn't.

由于计算的observable是属性,因此你不应期望
能够通过原型将它们添加到现有对象。

Since computed observables are properties, you shouldn't expect to be able to add them to existing objects through the prototype.