Search code examples
javascripthtmlknockout.jsknockout-3.0

How to use applyBindings for same element without using ko.cleanNode method


I'm creating simple application in KnockoutJS, here i need more input elements to update in a single button click. I have used ko.applyBindings(viewModel), but it throws below error.

Uncaught Error: You cannot apply bindings multiple times to the same element. at applyBindingsToNodeInternal (VM88 knockout-debug.js:3287)

I have found one solution, if i use ko.cleanNode(node) it solves my problem. But i don't want this because, i have many input elements. So obviously i need to clean each node for every button click. Any other solution in generic to use applyBindings for same element or else, i need to change core?

applybind = function() {
  viewModel = {
    nValue: ko.observable(10)
  }
  //ko.cleanNode(document.getElementById("txt")); // Don't want this.
  ko.applyBindings(viewModel);
}

ko.applyBindings({
  nValue: ko.observable(100)
}); //initial load.
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input type="text" id="txt" data-bind="value: nValue" />
<input type="button" value="update value" onclick="applybind()" />


Solution

  • In general ko.applyBinding method should be called only once. After that you can simply change observable values and changes will immediately be reflected in the UI. I've changed your snipped accordingly.

    viewModel = {
      nValue: ko.observable(100)
    }
    
    applybind = function() {
      viewModel.nValue(10);
    }
    
    ko.applyBindings(viewModel); //initial load.
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <input type="text" id="txt" data-bind="value: nValue" />
    <input type="button" value="update value" onclick="applybind()" />