addEventListener
will set the context (this
) of uploadCanceled
to xhr
:
function uploadCanceled(evt) {
console.log("Cancelled: " + this.status);
}
Example: http://jsfiddle.net/wJt8A/
If, instead, you need to trigger xhr.abort
through a "Cancel" click, you can return a reference and add any listeners you need after that:
function uploadFile() {
/* snip */
xhr.send(fd);
return xhr;
}
document.getElementById('submit').addEventListener('click', function () {
var xhr = uploadFile(),
submit = this,
cancel = document.getElementById('cancel');
function detach() {
// remove listeners after they become irrelevant
submit.removeEventListener('click', canceling, false);
cancel.removeEventListener('click', canceling, false);
}
function canceling() {
detach();
xhr.abort();
}
// detach handlers if XHR finishes first
xhr.addEventListener('load', detach, false);
// cancel if "Submit" is clicked again before XHR finishes
submit.addEventListener('click', canceling, false);
// and, of course, cancel if "Cancel" is clicked
cancel.addEventListener('click', canceling, false);
}, false);
Example: http://jsfiddle.net/rC63r/1/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…