2013-01-09 35 views
0

我有一個集合,它使用XMLHttpRequest成功發送文件到服務器。 但我不知道如何將函數附加到XHR2事件。集合中的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! 
    } 

}); 

爲什麼會這樣,我怎麼可以移動代碼發送的外()和成一個單獨的功能?

回答

0

你在調用函數​​而不是傳遞函數引用。嘗試

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

感謝穆薩,是有道理的:)順便說一句:_xhr.addEventListener( '負荷',this.onLoad) ; _也適用! –

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

});