Custom binding triggered by other bindings?

61 views
Skip to first unread message

Cardy

unread,
Nov 30, 2011, 7:29:47 AM11/30/11
to KnockoutJS
Hi all,

I have a worried feeling that this is 'by design', but I've recently
noticed that if one binding in my data-bind attribute is triggered, it
forces all the bindings in the data-bind attribute to be triggered.

Here's a fiddle which demonstrates it: http://jsfiddle.net/J6EPx/2/

Is this right or desired? (It isn't for me!)

I'm trying to develop a web app which requires different elements on a
div (say left and width) to be updated and animated (using a custom
binding) independently. Problem is, these non-animated bindings are
causing my animated bindings to be triggered again, causing a bit of
mess!

Any thoughts on this?

If it interests you lot, I've got a stack overflow question about the
same problem: http://stackoverflow.com/questions/8324454/why-is-my-knockoutjs-custom-binding-being-triggered

Thanks a lot!

Andy.

rpn

unread,
Nov 30, 2011, 8:14:19 AM11/30/11
to knock...@googlegroups.com
This is currently by design.  All bindings in a data-bind are triggered when any of bindings fire.  This is because they are all wrapped in a single dependentObservable.  In some cases, bindings have a dependency between each other (if options are updated, then value needs to run to ensure that it is still a valid value).  However, in some cases, this does cause a problem.

There is a different pattern that you can use when creating a custom binding that helps to mitigate this behavior.  Instead of defining the guts of your functionality in the "update" function, you would actually create your own dependentObservable in the "init" function.  It would look like:

ko.bindingHandlers.custBinding{
    initfunction(elementvalueAccessor{
        ko.dependentObservable({
            readfunction({
                ko.utils.unwrapObservable(valueAccessor());
                alert("custBinding triggered")
            },
            disposeWhenNodeIsRemovedelement
        });
    }
};

Reply all
Reply to author
Forward
0 new messages