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

前端 未结 7 1278
半阙折子戏
半阙折子戏 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:31

    you could override the bind method of jquery and thereafter and in the override store a reference of all the namespace and the corresponding events in an associative array and then access the array based on which namespace events you want to unbind. Code could be something like this

    var eventArray=[];
    (function ($) {
        var bind = $.fn.bind;
        $.fn.bind= function () {
        var result = bind.apply(this, arguments);
        var selector=arguments[0];
        var nameSpace= selector.split(".")[1];   //code to select the nameSpace eg. click.myNS o/p->myNS (update this if your selector has multiple '.')
        if(!eventArray[nameSpace])    //if the associative array does not contain the namespace yet
        {
           eventArray[nameSpace]=[];
        }
        eventArray[nameSpace].push(selector);
        return result;
    };
    })(jQuery);
    

    Now with the eventArray with you could unbind as you wish. Code to unbind all events on namespace myNS will look something as follows:

    $.each(eventArray['myNS'],function(){
       $(this).unbind();
    });
    

    Hope this is a good solution. please let me know if I made any mistakes.

提交回复
热议问题