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 に答える