How to add a computed observable via prototype
HTML
<script src="http://knockoutjs.com/js/knockout-2.0.0.js"></script>
<div data-bind="text: fullDomainName">test</div>
JavaScript
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);