简体   繁体   中英

How to wrap this behavior in a plugin?

Currently I have a request to have a Bullet Chart with two targets (min and max). To do it I am simply using a normal Bullet Chart with a Scatter series to draw the other target. I would like to wrap this behavior inside the bullet chart, so it would have something like the following options:

series: [{
    data: [{
        y: 275,
        target: 250,
        minTarget: 100
    }]
},

And then, on the wrap, I would get this minTarget and make a scatter plot automatically. How can I do it?

Here's the fiddle I have so far: http://jsfiddle.net/gwkxd02p/

I do not think that render is a good method to add another series - anyway, you can try to do it like this:

Highcharts.wrap(Highcharts.seriesTypes.bullet.prototype, 'render', function(p) {
  if (!this.hasRendered) {
    const scatterData = this.points
      .map(({ x, y, options }) => ({
        x,
        y: options.minTarget !== undefined ? options.minTarget : null
      }))

    if (scatterData.length) {
      const scatter = this.chart.addSeries({
        type: 'scatter',
        data: scatterData,
        marker: {
          symbol: 'line',
          lineWidth: 3,
          radius: 8,
          lineColor: '#000'
        }
      }, false)

      scatter.translate()
      scatter.render()
    }
  }

  p.call(this)
})

And data for bullet:

  series: [{
data: [{
  y: 275,
  target: 250,
  minTarget: 100
}, {
  y: 100,
  target: 50
}, {
  y: 500,
  target: 600,
  minTarget: 20
}]

live example: http://jsfiddle.net/n4p0ezzw/

I think that the better place is bullet's init method but in that method the points do not exist yet - so you would have to match the x values (if it is needed) on your own.

My suggestion is - do not wrap Highcharts if you don't have to. A better (simpler, safer, cleaner, easier to debug, it does not change Highcharts internal code) practice would be to wrap the Highcharts constructor in a function and parse the options inside it and then call the chart constructor with new options, like this:

function customBullet(container, options) {
  const newOptions = {} // parse options, check for minTarget, etc. and create new options

  return Highcharts.chart(container, newOptions)
}

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