【问题标题】:Access events of XHR2 in CollectionXHR2 在 Collection 中的访问事件
【发布时间】: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


    【解决方案1】:

    所以,感谢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!
        }
    
    }); 
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢 Musa,说得通 :) 顺便说一句:xhr.addEventListener('load', this.onLoad); 也可以!
      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多