2012-11-20 4 views
2

JSON 파일을로드하고 각 항목에 삽입하려고합니다.jQuery를 사용하여 녹아웃에서 관찰 가능한 배열에 삽입하는 좋은 방법

그래서 내가 가장 좋은 방법은 내가이 오류를

오류가 현재 시간에 각 기능

에서 관찰 배열에 삽입하는 방법을 궁금해

function ProductType(id, name) { 
var self = this; 

self.id = id; 
self.name = name; 
} 


function ProductsViewModel() { 
    var self = this; 
    var jqxhr = $.getJSON("data/product.json").success(function(data, status, xhr) { 
      self.products = ko.observableArray([  
     $.each(data.data.productTypeList, function(i,item){ 
      new ProductType(i, item.longName); 
    }) 
]);    
     }) 
    .error(function() { alert("error"); }) 
    .complete(function() { 
     console.log("fetch complete + " + this); 
    }); 

} 

이 코드를 가지고 : 500 오류 get/knockoutJQMProducts/# products 바인딩을 구문 분석 할 수 없습니다. 메시지 : ReferenceError : 제품이 정의되지 않았습니다. 바인딩 값 : foreach : products

하지만 각 결과 내에서 console.log (i)를 사용하면 결과가 반환됩니다.

감사

답변

3

ryadavilli의 대답은 좋지만, 배열을 캐싱 한 후 한꺼번에 observableArray를 설정하여 개선 될 수있다. 답에 대한

function ProductsViewModel() { 
    var self = this; 
    self.products = ko.observableArray(); 
    var jqxhr = $.getJSON("data/product.json").success(function(data, status, xhr) { 
     var products = []; 
     $.each(data.data.productTypeList, function(i, item) { 
      products.push(new ProductType(i, item.longName)); 
     }); 
     self.products(products); 
    }) 
     .error(function() { 
      alert("error"); 
     }) 
     .complete(function() { 
      console.log("fetch complete + " + this); 
     }); 
} 
+0

좋은 지적. 이렇게하면 녹아웃이 배열 변경시 보내는 알림 수가 줄어 듭니다. – ryadavilli

2

나는 당신의 VM 수정하고 관찰 할 수있는 배열이 성공을 채워되도록 성공하는 방법. 그러나 그것은 항상 존재합니다.

function ProductsViewModel() { 
    var self = this; 
    self.products = ko.observableArray();  
    var jqxhr = $.getJSON("data/product.json").success(function(data, status, xhr) { 
     // use this remove all only if you want to clear and load with new data. 
     self.products.removeAll(); 
     $.each(data.data.productTypeList, function(i,item){ 
      self.products.push(new ProductType(i, item.longName)); 
    }) 
    }) 
.error(function() { alert("error"); }) 
.complete(function() { 
    console.log("fetch complete + " + this); 
}); 
} 
+0

덕분에 .. 이제 어떻게 하나 개 이상한 것은 내 jQuery를 모바일 스타일링이 난 그냥 사용하는 경우처럼 해당 항목에 대한 일이 나던 것입니다 \t self.products = ko.observableArray ([ \t \t \t 새로운 ProductType ('1', '단') \t \t \t 새로운 ProductType ('2', 'S') \t \t \t]); 이유가 무엇입니까? – Dan

+0

HTML 바인딩 코드도 공유 할 수 있습니까? 또한 성공 호출에서 생성되는 객체를 확인하십시오. 당신이나 내가 일부 재산을 놓친 가능성이 있습니다. 또한, 배열 내의 각 객체 (각 ProductType)가 모두 문자열로 표시되는 것을 볼 수 있습니다. 아약스 데이터와 동일한 사건입니까? 그렇지 않으면 바인딩을 변경하거나 ProductType 반환 값의 속성을 변경하여이를 반영해야 할 수 있습니다. – ryadavilli

+0

다음은 제품 페이지를 새로 고치면 가 http://demo.stg.brightonconsulting.net.au/templates/tests/knockoutJQMProducts/ 먼저이 그 확인을 통과하지만 노트는 stying을 잃게 URL입니다 .. 내 모바일에서 두 번째 페이지 데이터가 나타나지 않는 경우에도 나타납니다! – Dan

관련 문제