$.get()
is asynchronous: Your code isn't going to wait there until $.get
sees a result. That result will come back a little bit later -- that's why you give it a callback, because it's not like a regular function call where the code waits until the result is handed directly to the caller. To stretch a metaphor, it's a bit like you're leaving a message. The server will be contacted, and the browser (via jQuery, yada) will call your callback in the near future when it gets a response from the server. In the meantime, your code will already have gone ahead and called alert
-- before the response has been received.
So, on to this
. this.verbs
is not the same as plain verbs
. Plain verbs
will refer to the one you declared in the var statement. They have nothing to do with each other. They have the same name, but they are different people living on different streets. As it happens, when you assign to this.verbs
, you're creating it as a member of a settings object internal to $.get
. That doesn't get you anything. Outside of the callback, this
will refer to the global window
object, unless you're writing your own class, which I doubt.
If you wanted to store verbs
in a place where other code can get to it, the plain verbs
at the top is the one to use.
The way jQuery uses this
is very unclear to new programmers, and there's a solid argument that it's a design flaw. Reasonable people disagree.
Case 1 is the only case that had the slightest hope of working, because it's the only one where you're assigning to outer-scoped verbs
and then passing the same variable to alert
. It failed anyway, for the timing reason given above.
Try assigning a placeholder value -- "initial verbs value"
-- to verbs
before you call this.importData()
. I expect that you will see that initial value in the alert
.
Try your alert
call INSIDE the $.get
callback. See what you get then. I'm pretty confident you'll see whatever you're getting from the server.
The code that makes use of verbs
should be called from that callback, the place where right now you're just assigning it to verbs
. The following is my preference. You could just stuff it all in the callback, and lots of people do.
this.importData = function() {
$.get("generator/parts_of_speech/verbs.txt", function(data) {
doStuffWithVerbs(data.split("\n"));
});
};
function doStuffWithVerbs(verbs) {
// Whatever you're doing with verbs goes here
}