Wednesday, 4 July 2012

Knockout binding doesn't work when using jquery $.load() method

So I encountered a problem today with knockout binding apparently not working when I load it via ajax using the $.load() method. I had the content loaded into a modal body, and the html content had data-bind elements in it, like so:




    <form id="create-form" class="form-horizontal"> 

     <fieldset> 

      <div class="control-group success"> 

       <label class="control-label">Email address</label> 

       <div class="controls"> 

        <span class="input-xlarge uneditable-input"><%= email %></span> 

       </div> 

      </div> 

      </div> 

     </fieldset> 

    </form>  



This is my js file that comes with it:




 ko.applyBindings(new CreatePageViewModel()); 

 function CreatePageViewModel() { 

   var self = this; 

   self.fetchContents = function() { 

     alert('hello'); 

   } 

 }  


Everything should work right? Wrong. Because we have already loaded the knockout library previously and it was activated, we need to specify the context in which to apply bindings, like so:



 ko.applyBindings(new CreatePageViewModel(), document.getElementById('create-form')); 

 function CreatePageViewModel() { 

   var self = this; 

   self.fetchContents = function() { 

     alert('hello'); 

   } 

 }  



No comments:

Post a Comment