使用KnockoutJS计算属性的原型

Ben*_*ter 6 knockout.js

是否建议在原型对象上创建计算属性?

这是我在下面尝试的但firstName绑定是将函数作为字符串返回而不是执行它(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);?
Run Code Online (Sandbox Code Playgroud)

And*_*ers 15

this不是实际的viewmodel,因为尚未创建实例.你可以做

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

ViewModel.prototype = {
   getFullName: function() {
      return this.firstName() + " " + this.lastName();
   }
};
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.这也是Ryan Niemeyer在[本视频]中提出的建议(http://vimeo.com/51103092) (3认同)