Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs: prevent event bubbling for elements with no handler

It seems like the binding <event>Bubble: false only works when there's a defined event handler (see Note 4) for <event>.

Here's an example fiddle.

For elements having native handlers for certain events (e.g. click: <textarea>, <a>, <select>, etc.), where the native handler suffices, I would expect setting the binding, e.g., clickBubble: false on them, without having to bind a "bogus" handler, to work.

I guess my question is, is there another knockout way to achieve this without extra bindings?

like image 280
Steven Avatar asked Dec 18 '12 22:12

Steven


1 Answers

The Bubble handlers are not actual binding handlers and are used as options in the event binding (click binding calls event binding). So, they do not run on their own.

So, you can add a "bogus" no-op handler and use clickBubble or you could certainly choose to create a custom binding to do this for you.

Maybe something like:

ko.bindingHandlers.preventBubble = {
    init: function(element, valueAccessor) {
        var eventName = ko.utils.unwrapObservable(valueAccessor());
        ko.utils.registerEventHandler(element, eventName, function(event) {
           event.cancelBubble = true;
           if (event.stopPropagation) {
                event.stopPropagation();
           }                
        });
    }        
};

And then just put:

<input data-bind="preventBubble: 'click'" />

You could also enhance it further to accept an array of events, if necessary.

Sample: http://jsfiddle.net/rniemeyer/WcXwZ/

like image 186
RP Niemeyer Avatar answered Oct 23 '22 02:10

RP Niemeyer