您如何解除特定命名空间中的所有jQuery事件的绑定?

nic*_*ckf 32 jquery events

在jQuery中是否存在"全局"unbind函数,这样我就能够从给定的命名空间中删除所有绑定事件?例如:

// assume these are the events bound to different elements
$('#foo').bind('click.myNS', ...);
$('#bar').bind('keyup.myNS', ...);
$('#baz').bind('dblclick.myNS', ...);    

// magic occurs here...
$.magicalGlobalUnbindFunction('.myNS');

// ...and afterwards, the three binds from above are gone
Run Code Online (Sandbox Code Playgroud)

我见过的所有非绑定示例都需要先选择一些元素.我认为从技术上讲,你可以这样做$('*').unbind('.myNS'),但这看起来非常低效.

mik*_*obi 13

您可以将myNS类添加到要取消绑定事件的每个元素中.


Mik*_*ike 11

您需要使用jQuery的OnOff方法.使用文档作为选择器.

$(document).off('.myNS');

$(document).on('click.myNS','#foo', ...);
$(document).on('keyup.myNS','#bar', ...);
$(document).on('dblclick.myNS','#baz',''');
Run Code Online (Sandbox Code Playgroud)

那你的方法可能会像

$(document).on('click.myNS','#foo', fooClicked);
var fooClicked = function(e){
    var $this = $(e.target);
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

  • 做得好!这是非常简洁的并且正确使用了命名空间。 (2认同)

fnc*_*omp 9

你总是可以包装$ .fn.bind,然后缓存必要的refs:

(function ($) {
    var origBind = $.fn.bind,
        boundHash = {};

    $.fn.bind = function (type, data, fn) {
        var namespace = '',
            events = [];

        if (typeof type === 'string') {
            // @todo check the allowed chars for event namespaces.
            namespace = type.replace(/^[^.]+/, '');

            if (namespace.length) {
                events = boundHash[namespace];

                // Namespaces can hold any number of events.
                events = boundHash[namespace] = $.isArray(events) ? events : [];

                // Only really need ref to the html element(s)    
                events.push({
                    type: type, 
                    fn: $.isFunction(fn) ? fn : data, 
                    that: this.length > 1 ? this.toArray() : this[0]
                });
            }
        }

        origBind.apply(this, arguments);
    };

    // namespace to be muffled. Feel free to qualify a specific event type.
    $.muffle = function (namespace, type) {
        var events = [];

        if (boundHash.hasOwnProperty(namespace)) {
            events = boundHash[namespace];

            $.map(events, function (event) {
                var _type = type || event.type;

                if (event.type.indexOf(_type) === 0) {
                    $(event.that).unbind(_type, event.fn);
                }
            });

            // @todo think of better return value.
            return true;
        }

        // @todo think of better return value.
        return false
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)