2013-06-05 3 views
0

필자는 뷰 모델에서 item.array_name 필드에 의해 명명 된 관찰 가능한 배열의 동적 배열을 구축하기 위해 다음 함수를 사용합니다. 그러나 나는 문서 객체로 배열을 채우는 것을 계속하고있다. 이것은 배열 당 페이지 내에서 동일한 HTML 인터페이스를 여러 번 재사용합니다. 누군가 내가 잘못된 방향으로 나를 가리킬 수 있습니까, 아니면 더 나은 접근 방법입니까?knockout.js에서 observableArray의 동적 배열을 만듭니다.

 self.getDocument = function(){ 
     //Reset arrays 
     self.documents.removeAll(); 

     //Dynamically build arrays 
     $.getJSON("/Documentation/Get-Section", function(allData) { 
      $.map(allData, function(item) { 
       var obj = {}; 
       obj[item.array_name] = ko.observableArray([]); 
       self.documents(obj)     
      }) 

     }); 

     //Add document object to the arrays 
     $.getJSON("/Documentation/Get-Document", function(allData) 
      $.map(allData, function(item) { 
       var temp_array = 'self.documents.'+item.array_name 
       eval(temp_array+'(new Document(item))') 
      }); 
     }); 

    } 

답변

2

나는 당신의 객체를 rejig 것 :

self.getDocument = function(){ 
    //Reset arrays 
    self.documents.removeAll(); 

    //Dynamically build arrays 
    $.getJSON("/Documentation/Get-Section", function(allData) { 
     $.map(allData, function(item) { 
      var section = { name: item.array_name, documents: ko.observableArray([])}; 
      self.documents.push(section); 
     }) 

    }); 

    //Add document object to the arrays 
    $.getJSON("/Documentation/Get-Document", function(allData){ 
     $.map(allData, function(item) { 
     var section = ko.utils.arrayFirst(self.documents(), function(documentSection) { 
      return documentSection.name === item.array_name; 
     }); 
      section.documents.push(new Document(item)); 
     }); 
    }); 
} 
+0

감사합니다! 이것은 훌륭하게 작동합니다. 배열 이름을 객체 내의 값으로 설정하는 것이 훨씬 더 좋습니다. Muchas gracias! – Wellso

+0

추가 된 쿼리와 마찬가지로 : 인터페이스를 구성하는 HTML 섹션을 다시 사용하기 위해 녹아웃 내에서 이러한 섹션을 반복 할 수있는 방법에 대해 알려줄 수 있습니까? – Wellso

+0

html의 foreach : documents 섹션을 사용하면 각 섹션에 사용됩니다. 엄밀히 말하면 문서가 아니라는 점을 감안할 때 문서 개체의 이름을 documentSections 또는 다른 것으로 변경하는 것이 좋습니다. –

관련 문제