How to properly control the context when using d3.json event handler

254 views Asked by At

I am trying to implement an asynchronous request with d3.js inside self-executing anonymous function.

Rather than saying d3.json(url, callback), I use d3.json(url) to first create the request object, then register a "load" event listener with xhr.on before starting the request with xhr.get.

Here is an example, in my object I have a render function that does render charts. I would like to call this render function once my data are loaded from an API. The call is made properly but inside my render function i am not able to call my parseData function. It seems that I have lost the this context.

The console throw this exception : Uncaught TypeError: this.parseData is not a function

Does I make something wrong ? Thanks

(function() {
  var Ploter = {
    render: function(jsondata) {
        this.parseData(jsondata); // where the error is raised
        // draw the line chart
        // ....
    },

    parseData: function(data) {
        console.log(data);
    },

    init: function() {
        this.bindEvents();
    },

    bindEvents: function() {
        var self = this;
        d3.json(this.DATAURL)
            .on("load", this.render)
            .on("error", function(error) { console.log("failure!", error); })
            .get();
    }
 Ploter.init();
})();
1

There are 1 answers

3
CupawnTae On BEST ANSWER

Instead of passing the function directly, you can wrap it in another function, creating a closure. The inner function will be able to reference the value you stored in self, which refers to the original Ploter you're looking for:

bindEvents: function() {
    var self = this;
    d3.json(this.DATAURL)
        .on("load", function(data) { self.render(data); })