将通过原型计算的可观察对象添加到构造函数中

Adding a computed observable via the prototype to a constructor function

本文关键字:添加 对象 构造函数 观察 原型 计算      更新时间:2023-09-26

我正在使用 Knockout.js 2.0,我正在尝试通过添加一个计算的可观察量来扩展我创建的构造函数的原型,但它会抛出"self"。IsSubDomain 不是一个函数"。如何解决此错误?有没有另一种方法来扩展构造函数来解决这个问题?

http://jsfiddle.net/StrandedPirate/J44S4/3/

注意:我知道我可以在构造函数的闭包中定义计算的可观察量,但我正在为挖空视图模型构建一个自动代码生成器,我需要能够通过原型属性扩展我的对象。

我也在论坛上回答了这个问题。

这里有一种方法可以做到这一点(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>

我已经在原型中定义了函数并使其成为计算在构造函数中可观察。

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

<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>

计算的底层读取函数将通过原型共享尽管实际计算的属性不会。我想可能有如果您创建了一些对象,然后在原型。新对象将使用新函数,但旧对象不会。

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