How do i get element bindings dynamically added?

119 views Asked by At

If i have a custom-binding that aggregates others like the following:

ko.bindingHandlers.binding1 = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var ctx = ko.utils.unwrapObservable(valueAccessor());

        ko.applyBindingsToNode(element, { 'binding2': ctx });        
        ko.applyBindingsToNode(element, { 'binding3': ctx });        
    }
};

"allBindingsAccessor" is returning only the current binding on its init function.

I was expecting that it returns binding1 and binding2 on binding2 "init" function and binding1, 2, and 3 on binding3 "init" function.

The following fiddle show the behaviour i mentioned. http://jsfiddle.net/J3sjq/5/

The problem is that my binding3 depends upon other bindings presence, like binding2 for instance.

What's the best way to implement that behaviour? I was thinking about modifying the context to inform of other bindings presence, but it sounded a little bit like a hack.

Thanks in advance.

EDIT:

I have updated my fiddle to show more of the original problem, i tried to simplify but i may have overdone it.

http://jsfiddle.net/J3sjq/6/

In the new fiddle, the binding1 is replaced by an initFieldStatus that initializes 3 other complex bindings each one calculating an input field status, the isInputAtWarning binding depends upon other bindings declared on the element.

Hopefully this will clarify the question.

Thankyou.

EDIT 2:

I provided a fiddle with a more real world example of what i am trying to implement.

http://jsfiddle.net/J3sjq/8/

1

There are 1 answers

1
Michael Best On BEST ANSWER

Rather than calling ko.applyBindingsToNode, you can directly call the init function of a binding.

ko.bindingHandlers.isInputAtWarning.init(
    element, function() { return observable.isInputAtWarning }, 
    allBindingsAccessor, viewModel, bindingContext);

http://jsfiddle.net/mbest/J3sjq/9/

But if you're only calling this directly, you might as well just make it a function.

function isInputAtWarning(element, value, allBindingsAccessor) {
    ...
}

...    

isInputAtWarning(element, observable.isInputAtWarning, allBindingsAccessor);