简体   繁体   English

在集合中访问XHR2的事件

[英]Access events of XHR2 in Collection

I have a Collection that sends files successfully to the server with XMLHttpRequest. 我有一个Collection,可以使用XMLHttpRequest将文件成功发送到服务器。 But I cannot figure out how to attach functions to the XHR2 events. 但是我不知道如何将功能附加到XHR2事件。

It only seems to be working when the code is directly inside of send() : 仅当代码直接位于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? 为什么会这样,以及如何将代码移出send()并移至单独的函数中?

You're calling the function with this.onLoad(xhr) rather than passing a function reference. 您正在使用this.onLoad(xhr)调用函数,而不是传递函数引用。 Try 尝试

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

So, thanks to Musa and Jonathan Lonowski I now have following, working code: 因此,感谢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!
    }

}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM