knockoutjs: prevent event bubbling for elements wi

2019-04-23 13:33发布

问题:

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?

回答1:

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/