> From: Jonas Galvez (via Patrick Hall)
> Is there any standardized way to preserve context when setting
> callbacks within an object's method? Here's how I see it is done now:
> 
> function Editor() { // class Editor
>   var self = this;
>   $(document).ready(function() { self.doSomething(); });
> }
> 
> Here's how I think it could be improved:
> 
> function Editor() { // class Editor
>   $(document).ready(function(ctx
> ) { ctx.doSomething(); }, this);
> }

No offense, but that seems more complicated to me. To use it, I have to
remember two rules:

1) The second argument to .ready() is an object.

2) This object is passed into the callback function as the first argument.

That's not too bad, but what about .hover()? It takes two callback
functions. I guess we will have to add that context object as the third
argument. Every jQuery method would have to have this extra argument added,
documented, and tested.

By contrast, for the first example all I have to remember is:

1) Lexical scoping always works, with any nested function, in any JavaScript
code.

And it requires no code in jQuery to implement this.

I think I can understand a possible motivation for the context argument
approach, having been through a similar discussion a few years ago at Adobe.
I was using closures extensively in the Acrobat multimedia JavaScript API
that I was developing. My manager, an outstanding C++ programmer, saw this
code and got a little freaked out - he asked me if I had a bug, because it
didn't possibly look like it could work. I explained about closures, but he
thought JavaScript programmers were unlikely to understand them or be
comfortable with them, so he insisted that we provide context arguments very
much like the one in your example.

In retrospect, I should have stood my ground. Closures may be a bit
discomforting when coming from other languages that do not encourage or
allow them (C++, Java, etc.), but they are so powerful and useful that it
pays to get familiar with them.

If there's another motivation for the context argument I'd be curious to
know what it is - I certainly may have overlooked something.

-Mike


_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to