KnockoutJs - 数据绑定不适用于新元素

Joe*_*ada 2 jquery knockout.js

我完成了绑定,它工作得很好.现在我试图通过jquery创建一个元素.我的问题是当我使用带有数据绑定的jquery创建一个新元素时它不会与knockout交互.请帮帮我:(我觉得这应该重新绑定.....

当我点击由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>
Run Code Online (Sandbox Code Playgroud)

我的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());
Run Code Online (Sandbox Code Playgroud)

提前谢谢!

小智 6

关于你想做什么我已经做了一个jsfiddle来告诉你如何:

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

我想解释一下这句话:

ko.applyBindings(new UserViewModel());
Run Code Online (Sandbox Code Playgroud)

通过编写该行,您要求knockout应用绑定,您可以在每次添加新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]);
});
Run Code Online (Sandbox Code Playgroud)