Applying bindings to multiple elements in knockout

427 views Asked by At

I have been using knockout for sometime now but I am stuck on this error "You cannot apply bindings multiple times to the same element". I have read through a few solutions here and was trying to use one of them.

Here is my code snippet

Applying the binding once the page is done loading

 $(document).ready(function()
        {
            $.each(sections, function(index0, v)
              {
                 console.log("I am here");
                  $.each(v, function(index1, v1)
                  {
                      console.log("went inside the looping statement");
                       console.log(index1);
                       ko.applyBindings(new Model, document.getElementById(index1));

                  });
              });
        });

The JSON through which I am calling the id's

var sections =
  {
    defects :
    {
        a : '',
        b : '',
        c : '', 
    }

  };

a,b,c are id's in my html code. Here is the code for ViewModel

 var Model = function()
  {
    var self = this;
      self.radio = function(key,key1)
       {
          console.log(key,key1);
          return;    
       }
   }

HTML Code

<tr  class=""   id="a" >
           <td>
               <div  class="col-lg-12 col-md-12 col-sm-12 col-xs-12 question" >
                   <label class="QuestionTextProperties">Question 1 </label>
               </div>
               <div class="btn-group col-lg-12 col-md-12 col-sm-12 col-xs-12" data-toggle="buttons">
                     <label  class="btn col-lg-6 col-md-6 col-sm-6 col-xs-6" >                              <input  type="radio"   name="a" data-bind="click:radio('defects','a')" class="a"   value="0"   id="a_No" ><i class="fa fa-circle-o "></i><i class="fa fa-check-circle-o "></i><span class="OptionsTextProperties">  No </span>                          </label>
                     <label  class="btn col-lg-6 col-md-6 col-sm-6 col-xs-6" >                              <input  type="radio"   name="a" data-bind="click:radio('defects','a')"  class="a"   value="1"   id="a_Yes" ><i class="fa fa-circle-o "></i><i class="fa fa-check-circle-o "></i><span class="OptionsTextProperties">  Yes </span>                           </label>
               </div>
           </td>
</tr>

Any help is really appreciated. Thank you in advance.

1

There are 1 answers

0
beauXjames On

If you can help it, you really only want to applyBindings once over the entire document. Think of your page as a view of your model and then create your model accordingly. There are many things that happen behind the scenes with the 'applyBindings' method, which creates lots of watchers and subscriptions.

The existing code you are using as an example isn't so clear such that an example solution can be made, however if you create your problem in Plunkr or some other cloud-based code haus, then better suggestions shall come.