I have a JavaScript widget as shown below that I'm converting to register with jQuery's event handlers (so I can call more than one event at a time.) It works fine when I assign my function to a local variable. When I refer to "this.myFunction" directly in the jQuery ready construct, I get "handler is undefined". Why is that? I'm not clear on why I need the extra level of indirection.
The "this" issue is one of my very few *major* beefs with JavaScript-the-language. It makes sense when you think about it, but JavaScript makes you think about binding more than a lot of other languages. It's the cause of a *lot* of bugs and questions, that's for sure.
Yes, it's unusual. Do you call MyWidget in top-level code?
Usually the document ready handlers (there can be as many as you like) are declared at top-level so that they register the ready handlers as the page is being evaluated prior to display.
Another jQuery best practice: unless it's necessary because a function is to be called from more than one location, the creation of named functions is regarded as needless. You'll generally see one-time functions declared inline as closures.
Bear,
I see. Now that you mention it, the ready part is redundant. MyWidget is instantiated in the initialization method (called from onload) in the main HTML. The fact that the code gets run implies the page has loaded. [And yes, I know this isn't a jQuery practice - the JSP I'm working on predates us using jQuery.]
Also good point about the unnecessary named function. it was there before I started changing things so I didn't think anything of it.