knockoutjs: prevent event bubbling for elements with no handler

南楼画角 提交于 2019-12-07 00:50:15

问题


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/



来源:https://stackoverflow.com/questions/13942279/knockoutjs-prevent-event-bubbling-for-elements-with-no-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!