knockout.jsko-custom-binding

knockout: add another binding in a custom binding init


I want to create a custom binding as a shorthand for adding other bindings -- like a macro.

<div data-bind="foo: 1"></div>

should do the same thing as

<div data-bind="click: clickHandler, css: { someClass: someObservable }, ...">
</div>

Something like:

ko.bindingHandlers.foo = {
    init: function(el,val,bindings,model,context) {
        // some way to add { click: clickHandler } to bindings()
    }
}

Solution

  • You can call ko.applyBindingsToNode from within the init of your binding handler like:

    ko.applyBindingsToNode({ click: someHandler, text: someText });
    

    If you are applying something like a control-flow, then you would want to pass the context in the second argument.