Jason
Jason

Reputation: 52533

jQuery: why does my live() handler declaration error out when the analogous click() one doesn't?

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??

Upvotes: 1

Views: 242

Answers (3)

Tgr
Tgr

Reputation: 28200

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

Upvotes: 0

spender
spender

Reputation: 120498

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.

Upvotes: 2

AllenJB
AllenJB

Reputation: 1255

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.

Upvotes: 5

Related Questions