2012-03-14 72 views
5

我想弄清楚如何最好地移除使用jQuery的匿名事件处理程序。正确删除匿名函数事件处理程序

我定义一个变量来保存我的jQuery对象:

var dom = $('#private-module'); 

后来在我的对象:

run: function() { 
    var button, that = this; 

    button = dom.append('<button class="btn">Click Me</button>'); 
    button.on('click', function(event) { 
     console.log('Clicked!'); 
     that.destroy(); 
    }); 
    }, 

    destroy: function() { 
    var button; 

    button = dom.find('.btn'); 
    button.off('click'); 
    } 

不管我做什么,我不能杀的按钮单击处理程序。感觉像我对范围的理解是有缺陷的。在这种情况下删除处理程序的首选方法是什么?我尝试了命名空间的事件和各种各样,但没有运气,所以我猜这是我忽略了一些简单的东西。也许我甚至不应该为事件处理程序使用匿名函数。

只是为了螺栓上的东西,以我的推理使用.append:

http://jsperf.com/jquery-append-vs-appendto

下面是最终的解决方案:

dom.append('<button class="btn">Send Message</button>'); 
button = dom.find('.btn'); 
button.on('click', function (event) { 
    sendTestMessage(); 
    that.destroy(); 
}); 

我也同意,并且要了解使用方法。一。感谢那。

+1

其实你应该使用'one'功能这一点。 – noob 2012-03-14 10:33:21

回答

7
button = dom.append('<button class="btn">Click Me</button>'); 

返回dom,而不是按钮,所以你绑定了事件处理函数dom

更改为:

button = $('<button class="btn">Click Me</button>').appendTo(dom); 

这里是working demo

+0

感谢您的解释和工作示例。对我完全意义。 – backdesk 2012-03-14 12:06:16

1

问题是buttondom,而不是.btn

button = dom.append('<button class="btn">Click Me</button>'); 

//a console.log(button) here reveals that button is "dom" 

//and thus you are adding a handler to "dom 
button.on('click', function(event) { 
    console.log('Clicked!'); 
    that.destroy(); 
}); 

一个办法做到这一点得益于.on()代表团权力是添加元素的子选择您想要的处理程序绑定第二个参数。

button.on('click', '.btn' function(event) { 
    //the value of "this" in here is the ".btn" 
    console.log('Clicked!'); 
    that.destroy(); 
}); 

破坏,我们使用.off()与有关.btn第二个参数:

button.off('click', '.btn'); 
+0

谢谢约瑟夫。你提供的例子似乎并不适合我,也许我错误输入了一些东西。请参阅上文以了解我所解决的问题。 – backdesk 2012-03-14 12:10:29