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?
Take advantage of the fact that they’re already closures, by setting a variable equal to
thisand then using that:All of the functions you define within
bindEvents“close over” the context of the call tobindEvents, and have access to the local variables associated with that call. Unlikethis, those variables don’t change depending on how the functions are called.This also has the advantage that you can use
thiswithin 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 yourclickhandler on#weight).