0

ノックアウト js を使用して並べ替えられたリストを作成しています。単純な観測可能な配列で動作するバージョンがありますが、json データとマッピング プラグインを使用して動作させるにはどうすればよいですか?

http://jsfiddle.net/infatti/x66Ts/

        // Here is my json data
        var viewModel;
        $.getJSON('http://echo.jsontest.com/name/Stuart', function (data) {
            viewModel = ko.mapping.fromJS(data);
            ko.applyBindings(viewModel);
        });

// Here is my working version of the simple observable array. How can it work using json data and the mapping plugin?
var ListSortModel = function () {

  // my items
    this.allItems = ko.observableArray([
        { name: 'Denise' },
        { name: 'Charles' },
        { name: 'Bert' }
    ]); 

    // sorter
    this.sortItems = function() {
        this.allItems(this.allItems().sort(function(a, b) { return a.name > b.name;}));
    };
};

ko.applyBindings(new ListSortModel());
4

1 に答える 1

0

あなたの要素はビューモデルの配列に<ul>バインドされています。allItemsしかし、結果をマッピングしているときは、観察可能なプロパティを持つ単一のオブジェクトしかありませんnameallItemsプロパティはありません。そのため、次のエラーが表示されます。

エラー: バインディングを解析できません。メッセージ: ReferenceError: allItems が定義されていません。バインディング値: foreach: allItems

別の問題は、応答で単一のアイテムを取得することです{"name": "Stuart"}(アイテムの配列ではありません)。allItemsそのアイテムをビューモデルのプロパティに割り当てることはできません。モデル アイテムを表示するには、そのアイテムを追加する必要があります。

var viewModel = new ListSortModel();
ko.applyBindings(viewModel);

$.getJSON('http://echo.jsontest.com/name/Stuart', function (data) {
    var item = ko.mapping.fromJS(data); // make it observable
    viewModel.allItems.push(item); // add to view model items
});
于 2013-05-28T16:26:31.327 に答える