Welcome to WebmasterWorld Guest from 54.227.127.109

Forum Moderators: open

Message Too Old, No Replies

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

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

Full Member

10+ Year Member

joined:Dec 8, 2005
posts: 231
votes: 0



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?
6:15 pm on Apr 2, 2015 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5012
votes: 23


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.
8:28 pm on Apr 2, 2015 (gmt 0)

Full Member

10+ Year Member

joined:Dec 8, 2005
posts: 231
votes: 0


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 :/)
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members