Search code examples
javascriptknockout.jsecmascript-5knockout-3.0

Custom Bindings in KnockoutJS


I just started out with KnockoutJS and ran into a problem with custom bindings. Im assigning an observable to the custom binding and change that observable through an input field. Another text field already reacts to changes but somehow the update doesnt get triggered.

ko.bindingHandlers.someBinding = {
  update: function(element, valueAccessor) {
    console.log("B");
  }
}

function myModel() {
  this.lastname = ko.observable("name");
}

ko.applyBindings(new myModel());

...

<p data-bind="text: lastname"></p>
<input data-bind="value: lastname" />
<p data-bind="someBinding: lastname" ></p>

https://jsbin.com/kupitepaxe/1/edit?html,js,console,output


Solution

  • It's just because you never access the observable within the binding, and so KO doesn't think you need that observable.

    Just access it, e.g.:

    var currentValue = ko.unwrap(valueAccessor());
    

    Normally, you would have done that as part of your binding handler because normally you need the value, but your initial test didn't do it, which is why you didn't get your expected result.

    Live Example:

    ko.bindingHandlers.someBinding = {
      update: function(element, valueAccessor) {
        console.log("B");
        ko.unwrap(valueAccessor());
      }
    }
    
    function myModel() {
      this.lastname = ko.observable("name");
    }
    
    ko.applyBindings(new myModel());
    <p data-bind="text: lastname"></p>
    <input data-bind="value: lastname" />
    <p data-bind="someBinding: lastname" ></p>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>