title: XMLHttpRequest and Binding a Callback not working
body: <p>I have a simple <code>get</code> function using <code>XMLHttpRequest</code> which accepts a callback parameter. The plan is to invoke the callback on the <code>onload</code> event handler.</p>
  
  <p>Here is a simplified version:</p>
  
  <pre><code>get(url,doit);
  
  function doit(data) {
      alert(data)
  }
  function post(url,callback) {
      var xhr=new XMLHttpRequest();
      xhr.onload=function() {                     //  Version 1
          callback(xhr.response)
      }
      xhr.onload=callback.bind(xhr,xhr.response); //  Version 2
      xhr.open('get',url,true);
      xhr.send(data);
  }
  </code></pre>
  
  <p>The callback function has one parameter, <code>data</code> which is supposed to be the response from the Ajax Call.</p>
  
  <p>I have 2 versions of invoking the callback:</p>
  
  <ol>
  <li>Version 1 simply calls the callback inside the event handler function.</li>
  <li>Version 2 uses <code>bind</code> to do the same; <code>this</code> is set to the <code>xhr</code> object, while the <code>xhr.response</code> is sent as the argument.</li>
  </ol>
  
  <p>When I use Version 1, everything works as expected. When I use Version 2, the <code>data</code> parameter is empty.</p>
  
  <p>I thought I knew <code>XMLHttpRequest</code> and <code>.bind()</code> reasonably well, but I cannot work out why the second version is empty. What is (not) happening here?</p>
  
  <p><strong>Comment</strong></p>
  
  <p>Thanks to the answers, I think I have it.</p>
  
  <p><code>.bind()</code> is executed immediately with the <em>current</em> value of <code>xhr.responseText</code>, which, at this stage, is nothing.</p>
  
  <p>It appears that the first Version is preferable if I need to respond with a <em>future</em> value.</p>
  
  <p>Thanks all.</p>