简体   繁体   中英

How to create zoomable plot object using flot library in javascript?

Here is my code so far. I can see the selection rectangle, but zooming isn't happening. what have I did wrong?

    function Plot(container, data) {
        this.options = {
            lines: {
                    show: true
                },
            points: {
                show: true
            },
            xaxis: {
                tickDecimals: 0,
                tickSize: 1
            },
            selection: { mode: "xy" }
        }
        console.log("script is running")

        this.data = []
        this.container = container;

        this.plot = $.plot(container, this.data, this.options);
        this.url = '/sensor/oscillogram_debug_data/'+110;

        this.container.bind("plotselected", this.zoom);
        this.zoom = function(event, reanges) {
            if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
                ranges.xaxis.to = ranges.xaxis.from + 0.00001;
            if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
                ranges.yaxis.to = ranges.yaxis.from + 0.00001;

            this.plot = $.plot(this.container, this.plot.getData(),
                          $.extend(true, {}, this.options, {
                              xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                              yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                          }));
        }


    }

    var plot = new Plot($("#output_plot_container"));

    var updateChart = function() {
        $.getJSON(plot.url, function(newdata) {
             for (var f_id in newdata)
                if (newdata.hasOwnProperty(f_id)) {
                    if (f_id='demodulated') {
//                        plot.plot.setData([newdata[f_id]])
//                        plot.plot.setupGrid()
//                        plot.plot.draw()
                    }

                }
        })
    }

A few problems here:

1.) You are binding to this.zoom before it exists, reverse those calls (and note typo in "reanges"):

 this.zoom = function(event, ranges) {
 ....
 this.container.bind("plotselected", this.zoom);

2.) Your attempt at some sort of OO scoping within this.zoom just isn't going to work. Once that function is bound, it doesn't have access to it's parent scope. If you want the this to be available in the bind, you can pass it in as eventData :

this.container.bind("plotselected", {obj: this}, this.zoom); // and replace the this in this.zoom with obj

Here's a working fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM