6

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

这是我在下面尝试过的,但是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);​
4

1 回答 1

16

this不是实际视图模型,因为尚未创建实例。你可以做

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

ViewModel.prototype = {
   getFullName: function() {
      return this.firstName() + " " + this.lastName();
   }
};
于 2013-01-02T11:36:06.220 回答