2

うまくいかない非常に単純な例があります。

jsfiddle: http://jsfiddle.net/ThomasDeutsch/8hzhp/3/

// My Model
function Customer(id, name, lastname) {
    this.Id = ko.observable(id);
    this.Name = ko.observable(name);
    this.LastName = ko.observable(lastname);
}

// My ViewModel
ViewModel = (function () {
    var getName = ko.computed(function (x) {
        return x.Name();
    });

    return {
        getName: getName(new Customer(1, "Thomas", "D"))
    };
})();

ko.applyBindings(ViewModel);​

問題:パラメータ (x) が定義されていません

目標:呼び出されたオブジェクトの Name-Property を返します - x をプロパティとして使用して、監視可能な Name プロパティを持つ任意のオブジェクトでこの関数を呼び出すことができるようにします

コードの説明: これは、knockout.js を含む Revealing-module-pattern を使用して行われます。Name-property は ko.observable() であるため、() が必要です。

質問: x が定義されていないのはなぜですか?

4

2 に答える 2

3

伺いします。x はどこで定義されていると思いますか?

getName を呼び出して Customer を渡していますが、getName はパラメーターを想定していません。

関数を次のように書き直すと、機能します。

var getName = function(x) { return ko.computed( function() {
    return x.Name();
})};
于 2012-06-03T19:38:16.463 に答える
1

監視可能な「getName」の値を変更しようとしていますが、これは計算された値であるため、これを処理する方法を指定するまでは未定義の動作です。

最善の解決策は、顧客を格納する別のオブザーバブルを導入することだと思います。

var ViewModel = (function() {
    // Observable for the customer
    var customer = ko.observable(new Customer(1, "Thomas", "D"));

    // The computed observable, using the other one
    var getName = ko.computed(function() {
        return customer().Name();
    });

    // If you only need to access the name, its sufficient
    // to export only that observable. However, this is still
    // read-only.
    return {
        getName: getName
    };
})();

書き込み可能にしたい場合は、計算されたオブザーバブルのセッターを定義できます。

var getName = ko.computed({
    read: function() {
        return customer().Name();
    },
    write: function(n) {
        customer().Name(n);
    }
});

(最も理にかなっている例ではありませんが、それは、ここで計算されたオブザーバブルを実際に必要としないためです)

于 2012-06-03T19:41:45.670 に答える