2012-10-17 63 views
1

我一直在爲此摔跤,我需要一些幫助。我有一個我用來渲染視圖的KO模型和視圖模型。在這種情況下,對象是一個樂隊。這個樂隊有一個可觀察的專輯陣列。我只是無法解決如何從樂隊模型中刪除專輯。如何從KnockoutJS的模型數組中刪除項目

function band(item) { 
    var self = this; 
    self.name = ko.observable(item.name); 
    self.country = ko.observable(item.country); 
    self.state = ko.observable(item.state); 
    self.city = ko.observable(item.city); 
    self.emailAddress = ko.observable(item.emailAddress); 
    self.albums = ko.observableArray(item.albums); 
} 

function User() { 
    var self = this; 
    self.bands = ko.observableArray([]); 
    self.singleBand = ko.observable(); 

    //Get Bands from data source and create new models to add to bands array 
    $.getJSON("/api/band", function (allData) {  
     $.each(allData, function (index, item) { 
      self.bands.push(new band(item)); 
     }); 
    }); 

    //function to get a single band from a rendered list 
    self.getThisBand = function (item) { 
     self.bands = ko.observableArray(null); 
     self.singleBand(item); 
    }; 

    //remove band from singleBands' album array 
    self.removeAlbum = function (albumToDelete) { 

     //how to delete album from band model 
    }; 
} 

ko.applyBindings(new User()); 

的邏輯很簡單,我得到的頻帶的列表,並將它們結合在UI(沒有probs)的列表。當我點擊UI中的樂隊名稱時,我加載getThisBand方法並填充UI(再次沒有概率)。我已經將singleBand.albums數組綁定到列表,並且具有femoveAlbum onclick函數。傳遞給函數的數據也是正確的對象。

有什麼基礎我失蹤?

回答

1

看起來self.singleBand()將等於當前的頻段,所以在你removeAlbum功能,你可以這樣做:

//remove band from singleBands' album array 
self.removeAlbum = function (albumToDelete) { 
    var band = self.singleBand(); 
    band.albums.remove(albumToDelete); 
}; 
+0

謝謝你這麼多!那就是訣竅。我一直在玩KO幾天,我喜歡它。謝謝你的協助! – ncbl

+0

太好了。很高興你到目前爲止享受它! –