JavaScript – Is $.proxy a Code Smell?

code smelljavascript

I've been writing most of my javascript applications in an OO style close to what I would use for most other languages. However, this means that most callbacks need to have a reference to an object, and I generally handle that by using $.proxy (or dojo.hitch, or whatever the framework's tool for this is) to be sure that the callbacks are operating in the context of my object, rather than the tag they were attached to.

Very quickly, this seems to lead to using proxied calls for almost everything, and can look like I'm fighting against the tool, particularly if the tool is jQuery.

Do you have a policy on how to handle javascript function binding in your work? Do you try fit your design to how the tool binds it's functions, or do you force the bindings to work according to your design?

Best Answer

Well the alternatives to function binding are a lot worse, instead of a simple $.proxy call, the popular alternative is to type this every time

var self = this;
$().click( function(e) {
    self.doit(e);
});

Compared to

$().click($.proxy(this.doit, this));

I have an active feature request for jQuery where this would be possible:

$().click(this);

This is what the standard event listener api supports:

elem.addEventListener("click", this);

The method .handleEvent is then called on this when the event occurs, with proper context. The element as this is just useless because it can be always attained from event.currentTarget.

So it's not a code smell in that you could replace it with something simpler or better.

Related Topic