2013-05-28 2 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

@imple이 더 많은 explantations로 업데이트되었습니다. –