Adding the calculated observable through the prototype to the constructor function

I am using Knockout.js 2.0 and I am trying to extend the prototype of the constructor function that I created by adding a computed observable, but its spread is "self.IsSubDomain is not a function". How to solve this error? Is there any other way to extend the constructor function to solve this problem?

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

Note. I know that I can determine the calculated observable inside the constructor function closure, but I am creating an automated code generator for knockout models, and I need to be able to extend my objects through the prototype property.

+7
javascript
source share
1 answer

I also answered this in the forum .

Here is one way to do this ( jsFiddle example ):

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

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

Here you can do a more general 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> 

The main function of reading computed will be used in conjunction with the prototype although the actual computed property will not. I suppose there could be confusion if you created some objects and then changed the function in Prototype. New objects will use the new function, but old objects will not.

Since computed observable objects are properties, you should not expect to be able to add them to existing objects through a prototype.

+5
source share

All Articles