0

我有一个使用 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()并放入单独的函数中?

4

2 回答 2

0

您正在调用函数this.onLoad(xhr)而不是传递函数引用。尝试

var self = this;
xhr.onload = function () {
    self.onLoad(xhr);
};
于 2013-01-09T01:28:03.117 回答
0

因此,感谢MusaJonathan Lonowski,我现在有了以下工作代码:

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();

        xhr.addEventListener('load', this.onLoad);

        data.append('file', file);

        xhr.open('POST', this.url);
        xhr.send(data);
    },

    /**
     * Respond to XHR2 'onload' event.
     *
     * No need to pass in the xhr object, since addEventListener
     * automatically sets 'this' to 'xhr'.
     */
    onLoad: function () {
        var response = $.parseJSON(xhr.responseText);
        console.log(response); // Works now!
    }

}); 
于 2013-01-09T02:18:41.670 回答