jquery - KnockoutJs - data-bind not working on new element -


im done on binding , works great. im trying create element create via jquery. problem when created new element using jquery data-bind doesnt interact knockout. please me :( think should rebind .....

when click add button created jquery doesnt work :(

this code: 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 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> 

my 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()); 

thanks on advance!

regarding trying have made jsfiddle show how:

http://jsfiddle.net/maw8k/4/

i explain line :

ko.applybindings(new userviewmodel()); 

by writing line, ask knockout apply binding, call each time add new dom element, failed try reapply existing binding.

because of last thing, must pass dom second argument delimit on dom need analyse , apply bindings.

another part of issue model. write model, must share it; otherwise list unique each binding.

for can that:

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 sharing model common list var userviewmodel = new userviewmodel(); //we inform knockout apply bindings ko.applybindings(userviewmodel);  //on click on btnadd $(".btnadd").bind('click',function(){   //we define new element   var newelement = $('<tr><td>joey</td> <td><input type="button" data-bind="click: adduser" value="add"/></td></tr>');   //we append   $('.user-list').append(newelement);   //we inform knockout apply binding on new element   //the second param must dom , not jquery why have use [0]   ko.applybindings(userviewmodel, newelement[0]); }); 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -