Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using prototype for KnockoutJS computed properties

Tags:

knockout.js

Is it recommended to create computed properties on the prototype object?

This is what I've attempted below but the firstName binding is returning 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);​
like image 492
Ben Foster Avatar asked Jan 02 '13 10:01

Ben Foster


1 Answers

this is not the Actual viewmodel since the instance is not created yet. You can do

ViewModel = function() {
   this.fullName = ko.computed(this.getFullName, this);
};

ViewModel.prototype = {
   getFullName: function() {
      return this.firstName() + " " + this.lastName();
   }
};
like image 62
Anders Avatar answered Nov 06 '22 15:11

Anders