Sixtease
Sixtease

Reputation: 790

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()
    }
}

Upvotes: 3

Views: 886

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

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.

Upvotes: 10

Paul Manzotti
Paul Manzotti

Reputation: 5147

Have you tried using jQuery in your custom binder:

ko.bindingHandlers.foo = {
    init: function(el,val,bindings,model,context) {
        $(el).attr('data-bind', 'click: clickHandler');
    }
}

Upvotes: 0

Related Questions