【发布时间】:2012-12-23 00:10:14
【问题描述】:
我有一个集合,它使用 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() 并放入单独的函数中?
【问题讨论】:
标签: javascript backbone.js xmlhttprequest