Search code examples
javascripttimeline.js

Javascript: Cannot call method of undefined


This may be a common error, but I can't find another way of doing this. I'm creating a timeline showing multiple projects using timeline.js with the following code

function createTimeline(){
        for(var length = data.section.length,i = 0; i < length; i++){
            var divWrapper = document.createElement("div");
            if(i != data.section.length - 1)
                divWrapper.setAttribute('class','timelineWrapper');
            $('body').append(divWrapper);
            layer[i] = new links.Timeline(divWrapper);
            links.events.addListener(layer[i], 'rangechange',
                function(){
                    var that = this;
                    var range = layer[i].getVisibleChartRange();
                    for (var j = 0; j < layer.length; j++){
                        if(j != i){
                            layer[j].setVisibleChartRange(range.start, range.end);
                        }
                    }
                }
            );
            layer[i].draw(data.section[i].project, options);   
        }
    }

It gives the error Cannot call method 'getVisibleChartRange' of undefined . What is the problem here? Why is layer[i] undefined? It is not being detected during the event rangechange itself.


Solution

  • You must bind i within a closure to save its value for your addListener call, as i is undefined when the function in your addListener later gets called. Try replacing the third argument of your addListener call with the below:

    (function(i) {
        return function() {
            var that = this;
            var range = layer[i].getVisibleChartRange();
            // Rest of code
        };
    }(i)); // Anonymous function binds i in a closure