psycotik psycotik - 13 days ago 5
Javascript Question

flot marking function, axes is not defined?

When I create a graph with the following options flot draws the graph properly:

var options = {
colors: trendcolors,
series: {
points: {
show: true
},
lines: {
show: true
}
},
xaxis: {
mode: "time",
axisLabel: "Date/Time",
tickLength: 0
},
yaxis: {
axisLabel: "Duration (Sec)"
},
selection: {
mode: "x"
},
grid: {
hoverable: true,
clickable: true,
markings: function (axes) {
var markings = [];
var date = new Date(axes.xaxis.min);
date.setUTCSeconds(0);
date.setUTCMinutes(0);
date.setUTCHours(0);
var i = date.getTime();
do {
markings.push({xaxis:{from: i, to: i + (24 * 60 * 60 * 1000) }, color: colormarking } );
i += ((24 * 60 * 60 * 1000) * 2);
} while (i < axes.xaxis.max);
return markings;
}
},
legend: {
labelFormatter: function(label, series) {
return label + " (" + series.data.length + ")";
}
}
};


However, when I change the marking anonymous function to a standard function an error occurs and flot fails to draw the graph because 'axes' is not defined on the fMarkings line. Why is this? What's different?

var options = {
colors: trendcolors,
series: {
points: {
show: true
},
lines: {
show: true
}
},
xaxis: {
mode: "time",
axisLabel: "Date/Time",
tickLength: 0
},
yaxis: {
axisLabel: "Duration (Sec)"
},
selection: {
mode: "x"
},
grid: {
hoverable: true,
clickable: true,
markings: fMarkings(axes)
},
legend: {
labelFormatter: function(label, series) {
return label + " (" + series.data.length + ")";
}
}
};


By the way, fMarkings is defined globally in another js block.

Answer

The markings argument expects a function or array. What you are doing though is calling a function while you are defining your options object. When you call it there the the axes variable doesn't exist. What you need is simply:

    grid: {
        hoverable: true,
        clickable: true,
        markings: fMarkings
    },

Where's fMarkings is a function like:

fMarkings = function(axes){
   return arrayOfMarkings
}
Comments