Wednesday, 15 July 2015

javascript - XMLHttpRequest and effects of scope -



javascript - XMLHttpRequest and effects of scope -

bounty note: simple question is, why don't need worry goget beingness removed before request finished if asynchronous request?

i have form generated php produces many html rows i'll refer "entries". each entry has 2 options, "delete" , "edit", each of may need create 0 or more xmlhttprequests.

to seek create handling requests manageable, made xmlhttprequest class, shown below:

function xmlhttprequest(inelement) { this.request = new xmlhttprequest(); this.write = inelement; var self = this; this.request.onreadystatechange = function() { self.write.innerhtml = (self.request.readystate == 4) ? self.request.responsetext : "please wait…"; } } xmlhttprequest.prototype.post = function(infile, inpost) { this.request.open("post", infile, true); this.request.setrequestheader("content-type", "application/x-www-form-urlencoded"); this.request.send(inpost); }

when either delete or edit clicked phone call functions, 1 of this:

function getform(inentryid, intemplateid) { var key = "form"+inentryid; if (!requested[key]) { var goget = new xmlhttprequest(document.getelementbyid("hideoptions"+inentryid)); goget.post("getform.php", "id="+inentryid+"&template="+intemplateid); } requested[key] = true; }

this appears work fine. however, after writing became worried when executions ends in getform() may possible goget removed before request finished , process not finish within function xmlhttprequest(), this.request.onreadystatechange = function().

is need worried (and have maintain kind of global connection each goget)?

edit: realize @ point after using while reply no, somehow not removed before finished request, want know why. also, decided remove side question (about prototype)

you quite right inquire question: according usual javascript memory management, goget , goes should garbage-collected.

however, since it's pretty mutual utilize pattern of xmlhttprequest invoke , forget it, there special rules preventing garbage collection in these cases.

the specs says here: http://xhr.spec.whatwg.org/#garbage-collection

4.2 garbage collection

an xmlhttprequest object must not garbage collected if state opened , send() flag set, state headers_received, or state loading , has 1 or more event listeners registered type 1 of readystatechange, progress, abort, error, load, timeout, , loadend.

if xmlhttprequest object garbage collected while connection still open, user agent must terminate request.

also here: http://www.w3.org/tr/xmlhttprequest/#garbage-collection (slightly different wording).

in practice, seems implementations may maintain xmlhttprequests lot longer that. you'll find long give-and-take on topic here: http://nullprogram.com/blog/2013/02/08/

javascript php ajax

No comments:

Post a Comment