gla*_*666 39 javascript jquery events
有没有人知道如何取消绑定事件处理程序集,但是记住它们以便以后再绑定它们?有什么建议?
ben*_*wey 23
项目数据中有一个事件元素.这应该是你的开始,你可以读取你的元素并在解除绑定之前将处理程序存储在一个数组中.评论您是否需要更多帮助.我从阅读$ .fn.clone方法中得到了这个想法,所以也看一下.
$(document).ready(function() {
$('#test').click(function(e) {
alert('test');
var events = $('#test').data("events");
$('#test').unbind('click', events.click[0]);
});
});
<a id="test">test</a>
Run Code Online (Sandbox Code Playgroud)
以下是如何实现这一点,提供选择方法storeEvents和restoreEvents方法.storeEvents在事件被调用时获取事件的快照.restoreEvents恢复到上一个上一个快照.可能需要稍微扭转它以便在恢复时参数化解除绑定,也许你想在最后一个快照之后保留绑定事件.
(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);
Run Code Online (Sandbox Code Playgroud)
由于jQuery 1.4.2+更改了事件处理程序的存储方式,因此这似乎相关:
我发现的最好方法是使用事件命名空间:
var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
for ( idx = 0; idx < ary_handlers.length; idx++ ){
$('#test').bind('click.foobar',ary_handlers[idx]);
}
// and then later:
$('#test').unbind('.foobar');
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,所有foobar事件都没有绑定.请注意,如果您需要更精细的粒度控制,则可以命名每个单击处理程序并与您的处理程序数组相关联:
var ary_handlers = [ fn_highlight, fn_onpress, fn_cleanup ];
for ( idx = 0; idx < ary_handlers.length; idx++ ){
$('#test').bind('click.ns_' + String(idx), ary_handlers[idx]);
}
// and then later you could pick off a specific one to unbind
$('#test').unbind('.ns_2');
Run Code Online (Sandbox Code Playgroud)