codebot
codebot

Reputation: 697

Synchronize x-axis zoom in multiple Highcharts-Vue stock charts

I am using Highcharts-Vue and I have multiple stockChart charts that I want to synchronize their x-axis zoom. So, when I zoom in one, all the others zoom at the same region.

I am trying to achieve the effect here and I also follow it as an example. But it is not written in vue.

My logic was to follow the code and in the afterSetExtremes events, I could call a vuex function to change the charts state and call setExtremes to all the other charts.

I tried to insert events in the xAxis in the object that contains the data and the options to create a chart. But this is created dynamically on the server and its passed to the front-end as a json, so the afterSetExtremes function does not work. So, this failed

Then, in my front-end vue I tried this

<highcharts 
  :constructor-type="'stockChart'" 
  :options="chart" 
  :callback="chartcallback" 
  @change="chartchange" 
  @click="chartclick" 
  v-on:afterSetExtremes="chartextremes" 
  v-on:zoom="chartzoom" >
</highcharts> 

and in my script

import { mapActions } from 'vuex';   
export default {
    name:'VesselCharts',
    props:['chart'], 
    methods:{
      ...mapActions(['zoomed']),    
      chartcallback(){
        console.log('chartcallback CHART LOADED'); 
      },
      chartchange(){
        console.log('CHART changed'); 
      },
      chartclick(){
        console.log('CHART clicked'); 
      },
      chartextremes(){
        console.log('CHART chartextremes'); 
      },
      chartzoom(){
        console.log('CHART chartzoom'); 
      }

    }
}

Except callback , all the other functions and events do not work. I dont see any console.log. So, this failed too.

I am stack.

How can I catch the zoom event and its xMin xMax and then call chart.xAxis[0].setExtremes(xMin, xMax, true, false); to all the other charts ?

Thanks

Upvotes: 0

Views: 850

Answers (1)

Wojciech Chmiel
Wojciech Chmiel

Reputation: 7372

The solution is to use Highcharts.addEvent method and listen to xAxis afterSetExtremes event (here EventBus is used to fire custom event called "extremes-changed" catched in the Chart component):

export function syncCharts(H) {
  H.addEvent(H.Chart, "load", function(e) {
    var chart = e.target;

    H.addEvent(chart.xAxis[0], "afterSetExtremes", function(e) {
      EventBus.$emit("extremes-changed", {
        min: e.min,
        max: e.max,
        chartId: chart.index
      });
    });
  });
}

Note, that this function can be saved to a separate file and initialized when chart component is created. Check demo posted below.

Demo:

API reference:

Upvotes: 2

Related Questions