I am trying to avoid \"const that = this\", \"const self = this\" etc. using es6. However I am struggling with some constructs in combination of vue js and highcharts where
The example illustrates the problem that persists in older libraries like Highcharts and D3 that emerged before current JS OOP practices and strongly rely on dynamic this
context to pass data to callback functions. The problem results from the fact that data is not replicated as callback parameters, like it is usually done in vanilla JS event handlers or jQuery callbacks.
It is expected that one of this
contexts (either lexical or dynamic) is chosen, and another one is assigned to a variable.
So
const that = this;
is most common and simple way to overcome the problem.
However, it's not practical if lexical this
is conventionally used, or if a callback is class method that is bound to class instance as this
context. In this case this
can be specified by a developer, and callback signature is changed to accept dynamic this
context as first argument.
This is achieved with simple wrapper function that should be applied to old-fashioned callbacks:
function contextWrapper(fn) {
const self = this;
return function (...args) {
return fn.call(self, this, ...args);
}
}
For lexical this
:
data () {
return {
highchartsConfiguration: {
formatter: contextWrapper((context) => {
// `this` is lexical, other class members can be reached
return context.point.y + this.unit
})
}
}
}
Or for class instance as this
:
...
constructor() {
this.formatterCallback = this.formatterCallback.bind(this);
}
formatterCallback(context) {
// `this` is class instance, other class members can be reached
return context.point.y + this.unit
}
}
data () {
return {
highchartsConfiguration: {
formatter: contextWrapper(this.formatterCallback)
}
}
}
If you need the this
that the formatter
method is called on, there is no way around an extra variable (that
, self
, whatever).