Using a prototype for KnockoutJS computed properties

Is it recommended to create calculated properties of the prototype object?

This is what I tried to do below, but the firstName binding returns the function as a string, rather than executing it ( http://jsfiddle.net/W37Yh ).

 var HomeViewModel = function(config, $, undefined) { if (!this instanceof HomeViewModel) { return new HomeViewModel(config, $, undefined); } this.firstName = ko.observable(config.firstName); this.lastName = ko.observable(config.lastName); }; HomeViewModel.prototype.fullName = function() { return ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); }; var model = new HomeViewModel({ firstName: "John", lastName: "Smith" }, jQuery); ko.applyBindings(model);​ 
+6
source share
1 answer

this not a real representation model since the instance has not yet been created. You can do

 ViewModel = function() { this.fullName = ko.computed(this.getFullName, this); }; ViewModel.prototype = { getFullName: function() { return this.firstName() + " " + this.lastName(); } }; 
+15
source

All Articles