As demonstrated in a similar inquiry about Vue, dealing with legacy libraries that rely on dynamic this
context instead of arguments for callback functions is a common issue.
Whenever feasible, it's advisable to utilize arguments. Some libraries advocate for using this
while also supplying necessary data as arguments, like so:
test.customEvent('changeEvent', e => {
console.log(e); // potentially an event
console.log(this); // vue instance
});
If the above approach is not applicable, one can resort to the self = this
workaround method:
const self = this;
test.customEvent('changeEvent', function () {
console.log(this); // event
console.log(self); // vue instance
});
An alternative solution that works well with pre-bound Vue methods is employing a helper function that passes dynamic context as an argument:
function contextWrapper(fn) {
const self = this; // works seamlessly with Vue methods
return function (...args) {
return fn.call(self, this, ...args);
}
}
...
setSwiper() {
const test = new something;
test.customEvent('changeEvent', contextWrapper(this.handleChange));
},
handleChange(e){
console.log(e); // event
console.log(this); // vue instance
}