I have the follo开发者_JAVA技巧wing 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??
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.
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.
Maybe the document.ready scope has another variable named myObject which hides the original one?
精彩评论