knockout.jsko-custom-binding

Knockout custom binding on button


I have some issues creating a custom binding. From what i understand the update callback of the binding should fire every time the view model changes.

I have created a small example.

http://jsfiddle.net/alexmaie/pbEmS/

  ko.bindingHandlers.testBinding = {

     update: function(element, valueAccessor, allBindingsAccessor, viewModel,       bindingContext) {
//just for testing purposes
     alert("update");
  }
};

$(document).ready(function() {
function AppViewModel() {
    var self = this;
    self.firstName = ko.observable("Bert");

}
ko.applyBindings(new AppViewModel());
});​

There i attach a binding to a button. The update of the binding is executed one time, and then never again, even if i change the data of the observable.

I want to use this approach to implement an canExecute binding.


Solution

  • Bindings are implemented inside of a computed observable, so they track dependencies based on the observables/computeds that are actually accessed.

    So, this means that in your update function, you would want to access the value of the observable that was passed to it like:

       ko.bindingHandlers.testBinding = {   
          update: function(element, valueAccessor) {
             //dependency is created here
             var value = ko.utils.unwrapObservable(valueAccessor());
             alert("update " + value);
          }
       }
    

    Updated fiddle: http://jsfiddle.net/rniemeyer/pbEmS/2/