0

I am looking into the source code of the openlayers javascript library. And in the file of source/CartoDB.js, I find there is something as following:

class CartoDB extends XYZ {
  constructor () {}
  initializeMap_() {
    ...
    const client = new XMLHttpRequest();
    client.addEventListener('load', this.handleInitResponse_.bind(this, paramHash));
    client.addEventListener('error', this.handleInitError_.bind(this));
    client.open('POST', mapUrl);
    client.setRequestHeader('Content-type', 'application/json');
    client.send(JSON.stringify(this.config_));
  }

  handleInitResponse_(paramHash, event) {
    ...
  }

  handleInitError_(event) {
    ...
  } 
}

I clean the code and remove the unrelated code for my question.
My confusing point is the following two lines:

client.addEventListener('load', this.handleInitResponse_.bind(this, paramHash));
client.addEventListener('error', this.handleInitError_.bind(this));

I think this.handleInitResponse_.bind(this, paramHash) just equals to this.handleInitResponse_ and this.handleInitError_.bind(this) just equals to this.handleInitError_. And these two methods are just defined in the CartoDB class.

So why handle it like this?

Chris Bao
  • 2,418
  • 8
  • 35
  • 62

1 Answers1

1

It's comparable with these two scenarios

var myObject = {
    readyState: "myObject",
    errorHandler: function() { console.log(this.readyState) },
    initialize: function() {
       var xhr = new XMLHttpRequest();
       xhr.addEventListener('error',this.errorHandler);
       xhr.open("GET", "http://invalid.com/invalid.dat", true);
       xhr.send();
    }
}
myObject.initialize(); // logs "4"

var myObject = {
    readyState: "myObject",
    errorHandler: function() { console.log(this.readyState) },
    initialize: function() {
       var xhr = new XMLHttpRequest();
       xhr.addEventListener('error',this.errorHandler.bind(this));
       xhr.open("GET", "http://invalid.com/invalid.dat", true);
       xhr.send();
    }
}
myObject.initialize(); // logs "myObject"
Mike
  • 16,042
  • 2
  • 14
  • 30