How to associate an event with only one object? jqplot

倖福魔咒の 提交于 2019-12-03 10:04:32

问题


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


回答1:


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!



来源:https://stackoverflow.com/questions/4491783/how-to-associate-an-event-with-only-one-object-jqplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!