在Collection中访问XHR2的事件

时间:2013-01-09 01:17:24

标签: javascript backbone.js xmlhttprequest

我有一个Collection,它使用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()之外并进入单独的函数?

2 个答案:

答案 0 :(得分:0)

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

var self = this;
xhr.onload = function () {
    self.onLoad(xhr);
};

答案 1 :(得分: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!
    }

});