Monday, 2 July 2012

Knockout calling view model method twice

So I have a pretty simple use case, which involves disabling a button until the person types something in the text field. Here is my view model setup:



 var pageViewModel = new PageViewModel(); 
 ko.applyBindings(pageViewModel);
 function PageViewModel() {
   var self = this;
   self.email = ko.observable("");
   self.hasEmail = ko.computed(function () {
     return self.email().length != 0;
   });
   //called after user clicks the create button.
   self.create = function () {
     $('#modal-body').load('http://localhost:1337/create', function () {
       $('#modal').modal();
     });
   }
 }  

In my view, this is what I have:


       <div id="search"> 
         <form name="input" action="" method="get">
           <input type="text" data-bind="value: email" value="The admin's email address" name="field"
               class="text"/>
           <input type="submit" data-bind="enable: hasEmail(), click: create()" value="Start" name="search" class="search btn"
               data-toggle="modal" href="#myModal"/>
         </form>
       </div>  

Now for some reason before I found out my problem, it was also calling the create() method whenever the ko.applyBindings() method is called.

Upon looking at the docs, I realized that I have an extra bracket on the create, which causes KO to evaluate the create in the beginning. So the correct code should look like this:


       <div id="search"> 
         <form name="input" action="" method="get">
           <input type="text" data-bind="value: email" value="The admin's email address" name="field"
               class="text"/>
           <input type="submit" data-bind="enable: hasEmail(), click: create" value="Start" name="search" class="search btn"
               data-toggle="modal" href="#myModal"/>
         </form>
       </div>  



No comments:

Post a Comment