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()) { </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()) { </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.
Michael best
source share