2013-05-28 25 views
0

我正在使用knockout.js構建一個排序列表。我有一個工作與一個簡單的可觀察數組的版本,但我怎樣才能使它與我的JSON數據和使用映射插件?使用knockout.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()); 

回答

0

<ul>元素綁定到allItems陣列視圖模型的。但是當你映射結果時,你只有一個具有可觀察屬性的單個對象name。沒有allItems屬性。所以,你只會收到一個錯誤:

Error: Unable to parse bindings. Message: ReferenceError: allItems is not defined; Bindings value: 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 
}); 
+0

我想仍然使用映射插件映射來自json的數據。 – simple

+0

@簡單更新,更多解釋 –