jQuery: Unbind event handlers to bind them again later

前端 未结 7 957
Happy的楠姐
Happy的楠姐 2020-11-27 03:58

Does anybody know how to unbind set of event handlers, but memorize them in order to bind them again later? Any suggestions?

相关标签:
7条回答
  • 2020-11-27 04:55

    Here is how to achieve that, provides a storeEvents and a restoreEvents methods on a selection. storeEvents takes a snapshot of the events on the moment it is called. restoreEvents restores to the last previous snapshot. Might need to twist it a little for parameterizing the unbinding while restoring, maybe you'd like to keep the bound events after the last snapshot.

    (function($){
    
        function obj_copy(obj){
                var out = {};
            for (i in obj) {
                if (typeof obj[i] == 'object') {
                    out[i] = this.copy(obj[i]);
                }
                else
                    out[i] = obj[i];
            }
            return out;
        }
    
    
        $.fn.extend({
    
            storeEvents:function(){
                this.each(function(){
                    $.data(this,'storedEvents',obj_copy($(this).data('events')));
                });
                return this;
            },
    
            restoreEvents:function(){
                this.each(function(){
                    var events = $.data(this,'storedEvents');
                    if (events){
                        $(this).unbind();
                        for (var type in events){
                            for (var handler in events[type]){
                                $.event.add(
                                    this, 
                                    type, 
                                    events[type][handler], 
                                    events[type][handler].data);
                            }
                        }
                    }
                });
                return this;
            }
    
        });
    })(jQuery);
    
    0 讨论(0)
提交回复
热议问题