2012-10-11 32 views
1

Im a knockoutjs新手,基本上我想在頁面上做的是,我加載激活詳細信息列表中的每個帶有刪除鏈接的視圖中的 與列表項目相關聯。每個激活細節項目包含三個屬性,索引,ActivationDate和ExpiryDate,例如 。如何更改knockoutjs observableArray的索引而不替換整個數組

var activationItem = { 
      'index': count, 
      'activationDate': item.activationDate, 
      'expiryDate': item.expiryDate 
     }; 

現在每次用戶點擊刪除任何特定項目。它應該重新排列所有的列表索引,以便仍然反映適當遞增的索引。例如1,2,3,4而不是1,3,4如果項目2被移除。

它是如何做到的,是取代陣列。如下:

 //Removes selected item from activationlist 
self.RemoveActivationListItem_Click = function() { 

    self.activationListItems.remove(this); 

    var count = 1; 
    var replaceArray = ko.observable([]); 

    //Re index all of the array items 
    ko.utils.arrayForEach(self.activationListItems(), function(item) { 

     var activationItem = { 
      'index': count, 
      'activationDate': item.activationDate, 
      'expiryDate': item.expiryDate 
     }; 

     replaceArray().push(activationItem); 

     count++; 

    }); 

    self.activationListItems.removeAll(); 
    self.activationListItems(replaceArray()); 

    TINY.box.show({ html: "Activation item removed", animate: true, close: false, boxid: 'message',autohide:5,top:90,left:0}); 

}; 

有沒有比這更好的方法?

回答

1

如果只想顯示index屬性,你可以使用$index淘汰賽對象foreach結合和KO他自己做所有的工作。看到這裏例如:http://jsfiddle.net/AfDQe/1/

如果你需要存儲在視圖模型指數,你可以簡化您的刪除功能:

self.RemoveActivationListItem_Click = function() { 
    self.activationListItems.remove(this); 
    var count = 1; 

    //Re index all of the array items 
    ko.utils.arrayForEach(self.activationListItems(), function(item) { 
     item.index = count; 
     count++; 

    }); 

    TINY.box.show({ html: "Activation item removed", animate: true, close: false, boxid: 'message',autohide:5,top:90,left:0}); 

}; 
+0

太謝謝你了。那正是我需要的。 – Vee