How would you unbind all jQuery events from a particular namespace?

前端 未结 7 1375
半阙折子戏
半阙折子戏 2021-02-06 22:50

Is there a \"global\" unbind function in jQuery, such that I\'d be able to remove all bound events from a given namespace? eg:

// assume these are the events bou         


        
7条回答
  •  自闭症患者
    2021-02-06 23:27

    You could always wrap $.fn.bind and then cache the necessary 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);
    

提交回复
热议问题