2013-09-22 25 views
0

JS:爲什麼這個挖空陣列不在DOM中更新?從我的ViewModel

self.newInterests = ko.observableArray(); 

self.saveNewInterest = function() { 
    // construct data and send to server 
    var payload = { 
     // data defined here 
    }; 
    var appendInterest = function(newInterest) { 
     self.newInterests().push(newInterest); 
    }; 
    interestservice().addInterest(payload, appendInterest); 
    self.closeModal(); 
}; 

interestservice.addInterest:

var addInterest = function (payload, callback) { 
    loadAnimate(); 
    var options = { 
     url: apiEndpoint + 'interest', 
     type: 'POST', 
     dataType: 'json', 
     data: payload, 
     xhrFields: { 
      withCredentials: true 
     } 
    }; 
    return $.ajax(options) 
     .done(function (response) { 
      toastr.success("Interest Added", "Success"); 
      callback(response); 
     }) 
     .fail(function (msg) { 
      toastr.error("Could not add interest.", "Error"); 
     }).complete(function() { 
      loadComplete(); 
     }); 
}; 
我認爲

<h3 data-bind="text: newInterests().length"></h3> 
<div data-bind="foreach: newInterests()"> 
    <p>new interest!</p> 
</div> 

如果我地初始化newInterests()與數據陣列,它顯示了在DOM中。如果我調試,我看到服務器的數據被添加到數組中,但視圖的綁定由於某種原因沒有被更新。任何想法發生了什麼?

回答

2

從newInterests中刪除(),它會正確更新。

<h3 data-bind="text: newInterests().length"></h3> 
<div data-bind="foreach: newInterests"> 
    <p>new interest!</p> 
</div> 

此外,當你推一個值,你並不需要先得到它 -

var appendInterest = function(newInterest) { 
    self.newInterests.push(newInterest); 
}; 
+0

哪一個?我認爲無濟於事。 – RobVious

+0

完美。這些圓括號在殺我!感謝您的幫助 – RobVious

+0

有幾條規則 - 在視圖中,Knockout已經爲您解開了可觀測(只要它是函數鏈上的最後一個) - 即。 this()。you()。嘿,當你想傳遞你使用parans的對象時,當你想傳遞值時使用()。祝你好運 –

相關問題