有人知道如何解除一组事件处理程序的绑定,但是记住它们以便以后重新绑定吗? 有什么建议吗?
有人知道如何解除一组事件处理程序的绑定,但是记住它们以便以后重新绑定吗? 有什么建议吗?
数据项中有一个事件元素。这应该可以帮助你入门,你可以读取你的元素并将处理程序存储在数组中,然后解绑定。如果需要更多帮助,请评论。我从阅读$.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>
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');
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');
以下是如何实现此功能,提供了选择器上的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);
编辑:修复了损坏的链接
unbind
,它将解除所有处理程序。除非你保留了对它们的引用,否则你将无法在以后重新绑定它们。你也可能会解除你不知道的事件 - 例如由另一个脚本绑定的事件。最好使用特定的处理程序调用 unbind,这样你就可以确信。 - meouwevent.handler
参数:$(document).ready(function() {
$('#test').click(function(e) {
e.preventDefault();
alert('test');
$('#test').unbind('click', e.handler);
//Do Something...
$('#test').click();
});
});
<a id="test">test</a>
event.handler
返回接收事件的当前处理程序,因此通过省略它,您可以保留其他处理程序。