2013-10-07 43 views
2

我在綁定上做了很多工作。現在即時通訊嘗試通過jQuery創建一個元素創建。我的問題是當我使用jquery創建了一個新的元素,並且它沒有與knockout進行交互。請幫我:(我想這應該是重新綁定.....KnockoutJs - 數據綁定不能在新元素上工作

當我點擊的jQuery它不工作:(

創建的添加按鈕這是我的代碼: HTML

User List:<br> 
<table> 
    <thead><tr> 
    <th>name</th><th>action</th> 
</tr></thead> 
<tbody class="user-list"> 
    <tr> 
     <td>anthony</td> 
     <td><input type="button" data-bind="click: addUser" value="add"/></td> 
    </tr>  
</tbody> 
</table> 

<input type="button" class="btnAdd" value="add User"/> 
User to Block:<br> 
<table> 
     <thead><tr> 
     <th>Username</th> 
    </tr></thead> 
    <tbody data-bind="foreach: users"> 
     <tr> 
      <td><input data-bind="value: name" /></td>  
     </tr>  
    </tbody> 
</table> 

我的JS:對提前

$(".btnAdd").bind('click',function(){ 
$('.user-list').append('<tr><td>joey</td> <td><input type="button" data-bind="click: addUser" value="Add"/></td></tr> ');}); 

function UserList(name) { 
    var self = this; 
    self.name = name; 
} 

function UserViewModel() { 
    var self = this; 

    self.users = ko.observableArray(); 

    self.addUser = function() { 
    self.users.push(new UserList("it works")); 
} 

} 
ko.applyBindings(new UserViewModel()); 

感謝

回答

6

關於你想做什麼我已經做了的jsfiddle向您展示如何:

http://jsfiddle.net/Maw8K/4/

我想解釋一下你該行:

ko.applyBindings(new UserViewModel()); 

通過編寫該行,請求敲除來應用綁定,每次添加新的DOM元素時都可以將其調回,但由於它會嘗試重新應用一些現有的綁定。

由於最後一件事,您必須通過DOM作爲第二個參數來界定哪些DOM需要分析和應用綁定。

您問題的另一部分是您的模型。在你寫模型時,你必須分享它;否則您的列表將對每個綁定都是唯一的。

對於您可以做這樣的:

function UserList(name) { 
    var self = this; 
    self.name = name; 
} 

function UserViewModel() { 
    var self = this; 

    self.users = ko.observableArray(); 

    self.addUser = function() { 
    self.users.push(new UserList("it works")); 
} 

} 

//We are sharing the model to get a common list 
var userViewModel = new UserViewModel(); 
//We inform knockout to apply the bindings 
ko.applyBindings(userViewModel); 

//On click on btnAdd 
$(".btnAdd").bind('click',function(){ 
    //We define the new element 
    var newElement = $('<tr><td>joey</td> <td><input type="button" data-bind="click: addUser" value="Add"/></td></tr>'); 
    //We append it 
    $('.user-list').append(newElement); 
    //We inform knockout to apply the binding only on the new element 
    //The second param must be DOM and not JQuery so that why you have to use [0] 
    ko.applyBindings(userViewModel, newElement[0]); 
}); 
+0

非常感謝你!這解決了我的問題! :) –

0

「對不起爲t!他承擔了壞消息,但你現在正在使用Knockout.js,而jQuery應該是你從過去記得的東西,但是隻在需要時才使用。忘掉DOM操作,期待雙向數據綁定。

您在視圖模型上的addUser方法永遠不會被調用,因爲您沒有綁定它。查看Knockout教程以更好地瞭解如何使用它們。

<input type="button" class="btnAdd" data-bind="click: addUser"/> 

self.addUser = function() { 
    alert('OMGooses!'); 
    self.users.push(new UserList("it works")); 
}; 

每當你嘗試使用綁定處理程序使用數據綁定=「」屬性不是你自己的事情。您也可以使用無容器綁定,但請在文檔中查找如何執行此操作。

+0

謝謝:)我想我應該改變我的部件與KO工作。 –

0

新的元素上做ko.applyBindingsToNode

+0

要打開,請避免jquery,並去自定義綁定或純JavaScript。 –

相關問題