1

我有以下代码:

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范围内调用?

4

1 回答 1

3

利用它们已经是闭包的事实,通过设置一个等于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 also has the advantage that you can use this within the event handlers with its jQuery meaning, the element on which you hooked the event (this saves your looking it up again, for instance within your click handler on #weight).

于 2012-12-05T11:37:48.860 回答