Forum Moderators: open

Message Too Old, No Replies

why must a callback on onreadystate be inside an anonymous function?

         

lethal0r

5:45 pm on Apr 2, 2015 (gmt 0)

10+ Year Member




function works(callback) {
onreadystate = function() {
callback(xmlhttp.responseText);
}
}
works(callback);

the callback function can access xmlhttp.responseText

function fails(callback) {
onreadystate = process_response(callback);
}

function process_response(callback) {
callback(xmlhttp.responseText);
}
fails(callback);

the callback function does not receive xmlhttp.responseText

can anyone tell me why the second method fails? and for bonus points, why this does not flag an error in the console?

Fotiman

6:15 pm on Apr 2, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I see a few issues in your examples:
1. onreadystate seems to be defined as a global variable.
2. xmlhttp also seems to be defined as a global variable.

In your first example, onreadystate is assigned a function reference. In your second example, onreadystate is assigned THE RESULT of executing a function. Instead, what you want is to call the "bind" method on the function that you want assigned to onreadystate. The bind method returns a function reference that executes with a particular context. Here's how your code would change:

function fails(callback) {
onreadystate = process_response.bind(this, callback);
}

Note, I passed in "this" as the context (with "this" being whatever the context is when your fails method is called (probably window), but you might change that if it's not the object you want to be in context when process_response executes.

lethal0r

8:28 pm on Apr 2, 2015 (gmt 0)

10+ Year Member



onreadystate is assigned a function reference. In your second example, onreadystate is assigned THE RESULT of executing a function


that's it right there. thank you so much!

I think w3schools [w3schools.com] have misled me by stating:

onreadystatechange - Stores a function (or the name of a function) to be called automatically each time the readyState property changes


the bit in italics misses a nuance - if the function being referenced needs an argument passing in, it can't be referenced by name as using the brackets will force it to be called. at least i've learnt something (in about 6 hours :/)