【问题标题】:jQuery $.proxy scopejQuery $.proxy 范围
【发布时间】:2012-11-23 05:28:45
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: jquery oop scope


    【解决方案1】:

    利用他们已经是closures这一事实,设置一个等于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含义是你钩住事件的元素(这可以节省你再次查找它,例如在你的click处理程序中#weight)。

    【讨论】:

    • @AllysondePaula:不用担心,很高兴有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多