2

So I got jquery flot chart that uses a tick formatter to display my values correctly.

The graph could have multiple axes and to generate them correctly I used a loop that contains my formatter function.

for (var i = 0; i < axis.xaxis.length; i++) {
    var format = format || "HH:mm";

    var tickFormatter = function(val, axis) {
        return ValueToTime(Math.abs(val), format, true);
    };

    myAxes.xaxis.push({
        tickFormatter: tickFormatter,
        tickSize: tickSize,
        position: thisPos || "left"
    });
}

When the formatter is executed format is undefined therefore all my labels also appear as 'undefined'.

Is it possible to pass my variable to the function?

Please note: the function gets called inside the plugin which I wish not to edit as it is open source.

ChiMo
  • 581
  • 2
  • 13
  • 32

2 Answers2

1

Use another function to create the different tick formatters, this way you get a closure over each format string:

function getTickFormatter(format) {
    return function(val, axis) {
        return ValueToTime(Math.abs(val), format, true);
    };
}

for (var i = 0; i < axis.xaxis.length; i++) {
    var format = format || "HH:mm";

    var tickFormatter = getTickFormatter(format);

    myAxes.xaxis.push({
        tickFormatter: tickFormatter,
        tickSize: tickSize,
        position: thisPos || "left"
    });
}

For more information on closures see this questions:

Community
  • 1
  • 1
Raidri
  • 17,258
  • 9
  • 62
  • 65
0

So it seemed like the only answer suggested didn't work so well...

Didn't Work So Well

However what does work is passing my format variable through the plugin's options.

for (var i = 0; i < axis.xaxis.length; i++) {
    var format = format || "HH:mm";

    var tickFormatter = function (val, axis) {
        return ValueToTime(Math.abs(val), axis.options.format, true);
    };

    myAxes.xaxis.push({
        tickFormatter: tickFormatter,
        tickSize: tickSize,
        format: format,
        position: thisPos || "left"
    });
}

This did work

I do realise that flot has a 'time' format but the functionality of this is very limited, especially when my clients are extremely picky about the minute details .

ChiMo
  • 581
  • 2
  • 13
  • 32