我有一个使用 XMLHttpRequest 将文件成功发送到服务器的集合。但我无法弄清楚如何将函数附加到 XHR2 事件。
仅当代码直接位于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!
}
});
为什么会这样,如何将代码移出send()并放入单独的函数中?