I have a Collection that sends files successfully to the server with XMLHttpRequest. But I cannot figure out how to attach functions to the XHR2 events.
It only seems to be working when the code is directly inside of send():
var Photos = Backbone.Collection.extend({
url: config.url,
/**
* Send file to server.
* @todo Should Backbone.sync be overwritten instead?
*/
send: function (file) {
var data = new FormData(),
xhr = new XMLHttpRequest();
// ======> Doesn't work:
xhr.addEventListener('load', this.onLoad(xhr));
// ======> Doesn't work either:
xhr.onload = this.onLoad(xhr);
// ======> But this works:
xhr.onload = function () {
var response = $.parseJSON(xhr.responseText);
console.log(response); // Works!
};
data.append('file', file);
xhr.open('POST', this.url);
xhr.send(data);
},
/**
* Respond to XHR2 'onload' event.
*/
onLoad: function (xhr) {
var response = $.parseJSON(xhr.responseText);
console.log(response); // Doesn't work!
}
});
Why is that so, and how can I move the code outside of send() and into a separate function?