Ragen Dazs
Ragen Dazs

Reputation: 2170

jQuery $.proxy scope

I have the following code:

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));

},

How can I reduce this repetive code $.proxy call as all methods inside bindEvents will be need call in this scope?

Upvotes: 1

Views: 159

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074455

Take advantage of the fact that they're already closures, by setting a variable equal to this and then using that:

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();
    });

},

All of the functions you define within bindEvents "close over" the context of the call to bindEvents, and have access to the local variables associated with that call. Unlike this, those variables don't change depending on how the functions are called.

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).

Upvotes: 3

Related Questions