I’ve been through a ton of posts and I finally got what I needed thanks to this:
$("a.foo").click(function(){
var that = this;
jPrompt("Type something:","","", function(r) {
$(that).text(r);
}
}
From the following:
Accessing $(this) within a callback function
I was wondering if someone could expand on what exactly is happening here (why is this not available without re-assigning?) and what core information I should read up on? From what I gather this might have something to do with closures… that’s most of what I bumped into while searching around. Is that accurate?
In my case, I was looking to execute some code, then redirect once an ajax request completed. In the callback function I was running $(this).attr("href") which was returning undefined.
thisis assigned by javascript according to how a function is called. So, it is thejPrompt()function that determines what valuethiswill have in your callback whenjPrompt()calls the callback.So, unless jPrompt goes out of its way to keep the same value for
thisvia some argument you passed in, it will likely have a different value. As such, you can save it away for access within the callback as you’ve done. This is a very common design pattern in javacscript callbacks.FYI, some of the ways that
thisis assigned:obj.method()–thisinmethod()will be set toobjfunc.call(obj)–thisinfunc()will be set toobjfunc()–thiswill be set towindowinfunc()orundefinedin strict mode