Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate an event with only one object? jqplot

Im using jqplot to draw some charts. It is a great tool, but it lacks a simple clickhandler option for each chart.

Its plugins like highlighter, draggable and cursor register their interest in capturing click/mouse-events from the jqplot canvas by adding themselves to jqplot.eventListenerHooks (eventListenerHooks.push(['jqplotClick', callback]); for example. or 'jqplotMouseDown' or such are also available.

After making my plot with the usual $.jqplot(target, data, options); then I do this

$.jqplot.eventListenerHooks.push(['jqplotClick', myFunc]);

and sure enough myFunc gets called wherever I click on the plot, with event, neighbour, datapos and gridpos. Neighbour is the most interesting, it contains my data point if there was a click on it. This is the data I need to make a popup close to the gridpos with aditional information on the datapoint.

But the problem is if I have two charts on the same page and want to register different callbacks for each jqplot. As it is now, when I register the second myFunc2, all the clicks on the second plot go through the myFunc aswell!

Do I need to make changes to jqplot? Any directions, whatsoever?

Thanks

like image 248
rapadura Avatar asked Dec 20 '10 16:12

rapadura


1 Answers

This isn't well-documented, but you can find a discussion about it here.

Basically, you need to create event handlers for your chart before calling jqplot to create the actual chart. To do that, you need to do something like this:

var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
};

$.jqplot.eventListenerHooks.push(['jqplotClick', handler]);

That's just a simple event handler that checks to see if there's a neighboring data point near where you clicked. See a working example here: http://jsfiddle.net/andrewwhitaker/PtyFG/

Update: If you want to only listen to events on a certain plot, you could do something like this:

var handler = function(ev, gridpos, datapos, neighbor, plot) {
    if (plot.targetId === "#chartdiv") {
        if (neighbor) {
            alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
        }
    }
    else if (plot.targetId === "#chart2div") {
        ....
    }
    // etc...
};

Where you would replace #chartdiv with whatever the Id of the chart you want to listen to events for is. The example has been updated.

Update 2: Looks like you can use a regular bind event with the plot events:

$("#chartdiv").bind("jqplotClick", function(ev, gridpos, datapos, neighbor) {
    if (neighbor) {
        alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
    }
});

Example using this method, with 2 charts:

http://jsfiddle.net/andrewwhitaker/PtyFG/5/

Hope that helps!

like image 69
Andrew Whitaker Avatar answered Nov 15 '22 00:11

Andrew Whitaker