0

I have a Collection that sends files successfully to the server with XMLHttpRequest. But I cannot figure out how to attach functions to the XHR2 events.

It only seems to be working when the code is directly inside of 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?

John B.
  • 2,309
  • 5
  • 23
  • 22

2 Answers2

0

You're calling the function with this.onLoad(xhr) rather than passing a function reference. Try

var self = this;
xhr.onload = function () {
    self.onLoad(xhr);
};
Musa
  • 96,336
  • 17
  • 118
  • 137
0

So, thanks to Musa and Jonathan Lonowski I now have following, working code:

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!
    }

}); 
Community
  • 1
  • 1
John B.
  • 2,309
  • 5
  • 23
  • 22