取消绑定所有事件处理程序,执行某些操作,然后使用jquery再次绑定

时间:2014-05-03 00:25:52

标签: jquery bind unbind

我试图存储元素的所有事件处理程序,然后取消绑定它们,然后执行某些操作然后再次绑定,但是当我取消绑定处理程序时,显然处理程序的变量被修改为空对象

  var events = $._data(this.$element.get(0), 'events');
  console.log(events);    //here the variable events contains an object with the handlers
  this.$element.unbind();
  console.log(events);   //here the variable events contains an empty object

  //function to bind again the handlers
  $.each(events, function() {
    // iterate registered handler of original
    $.each(this, function() {
      $('#target').bind(this.type, this.handler);
    });
  });

1 个答案:

答案 0 :(得分:1)

您可以在深层模式下使用extend复制events中的数据:

var events = $._data(this.$element.get(0), 'events'),
    eventsCopy = $.extend(true, {}, events);
this.$element.unbind();
$.each(eventsCopy, function() {
    $.each(this, function() {
        $('#target').bind(this.type, this.handler);
    });
});