我有以下代码:
bindEvents: function() {
$('#weight').click($.proxy(function(){
this.changeWeight($('#weight').is(':checked'));
},this));
$('#produce').change($.proxy(function(){
this.changeProduce();
},this));
$('.help-gtin').click($.proxy(function(){
if ($('#help-gtin').is(':hidden')) {
$('#help-gtin').slideDown();
} else {
$('#help-gtin').slideUp();
}
this.refreshGtin();
},this);
$('[name="order_production"]').click($.proxy(function(){
this.changeProduction();
},this));
},如何减少重复代码$.proxy调用,因为bindEvents中的所有方法都需要在this作用域中调用?
发布于 2012-12-05 11:37:48
利用它们已经是闭包的事实,设置一个等于this的变量,然后使用该变量:
bindEvents: function() {
var self = this; // <==== Set the variable
$('#weight').click(function(){
// v--- Use it (throughout)
self.changeWeight($('#weight').is(':checked'));
});
$('#produce').change(function(){
self.changeProduce();
});
$('.help-gtin').click(function(){
if ($('#help-gtin').is(':hidden')) {
$('#help-gtin').slideDown();
} else {
$('#help-gtin').slideUp();
}
self.refreshGtin();
});
$('[name="order_production"]').click(function(){
self.changeProduction();
});
},在bindEvents中定义的所有函数“关闭”调用bindEvents的上下文,并访问与该调用相关的局部变量。与this不同,这些变量不取决于函数的调用方式。
这也有一个优点,您可以在事件处理程序中使用this (它的jQuery含义是连接事件的元素)(这将节省您再次查找它,例如在#weight上的click处理程序中)。
https://stackoverflow.com/questions/13722376
复制相似问题