views:

102

answers:

3

I have the following in a javascript file (using jQuery as well):

$(function(){
    $('#mybutton').live('click',myObject.someMethod);
});

var myObject = { 
    someMethod: function() { //do stuff }
};

I get a js error on pageload that says "myObject isn't defined". However, when I change the event handler in the doc.ready function to:

$('#mybutton').live('click', function(){ myObject.someMethod(); });

it works! I have code structured like the first example all over my codebase that works. W T F??

+5  A: 

In the first code block, you're trying to assign the value of myObject.someMethod (which is declared after this code block) to the second parameter for live().

When you wrap it in an anonymous function, as in the second block, the anonymous function doesn't get executed until the live event gets triggered. myObject.someMethod has been created by this point, so the code works as expected.

AllenJB
here's a bit of working code from another file: `$(function(){ $('td.select-ad input').live('change', AdPreview.selectAd); });` `var AdPreview = { ... , selectAd: function() { //do stuff } ... }` now why does this bit of code work and not the one i presented in the question??
Jason
also, it shouldn't matter whatever i'm declaring in the first block first because the first block doesn't run until page load, whereas the object declaration runs immediately upon script load....
Jason
What if the page is already loaded? From the docs: "If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately." Looks like this might be the difference.
spender
+2  A: 

In the second case the lookup on myObject is deferred until the point at which the click handler is executed. In the first case, (in some cases, see below) the lookup must be immediate... as myObject is not yet defined, you get an error. Is there any reason not to add the event handler after myObject has been declared and assigned?

EDIT

As commented above, is it possible that this code is running after the .ready() event has fired.

jQuery docs say this about the .ready() method:

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

In this case, your ready handler will fire synchronously, thus requiring myObject to be defined.

spender
A: 

Maybe the document.ready scope has another variable named myObject which hides the original one?

Tgr
well... myObject isn't really the name. i generalized the code. this would be a good guess but a search of my code shows that there are no variables with that name (the actual name is "Conversions", which is a brand new object introduced today, and this is the first js I've written for it :\ ). thanks tho!
Jason