I have a simple Ionic Page containing a 'global' variable called 'mood', accessible like 'this.mood'.
Inside a function of my page I make use of an intro.js library callback. This is my code:
import introJs from 'intro.js/intro.js';
[...]
var mood;
[...]
this.introJsVar=introJs.introJs();
this.mood='init';
[...]
intro() {
var tutorialSteps={ steps: [{
element: 'somelementid',
intro: 'Hello world',
position: 'right'
}] }
this.introJsVar.setOptions(tutorialSteps);
this.mood='foo'; // This works
console.log(this.mood); // logs 'foo'
this.introJsVar.onchange(function(targetElement) {
this.mood='bar'; //This DOES NOT work
});
this.introJsVar.start();
}
}
How may I modify the value of the variable 'mood' inside the callback?
It seems that inside the callback onchange the previous context gets lost: 'this' contains a lot of variable useful to the library intro.js but lose the variables declared and used in the previous context, that is the one of the page... An explanation of what is going on it would be also very appreciated.
EDIT (secondary problem and solution): Truly, I need to access both contexts: the one of the Ionic page (outer) which contains the variable 'mood' and the one of the callback onchange (inner) which contains info about the change happened (which triggered the callback), like the number of step of the intro.js tutorial the user has changed to, that I was able to find in 'this' before using arrow function. ( variable '_currentStep': https://introjs.com/docs/intro/api/#introjsonchangeprovidedcallback)
I can solve the main problem using an arrow function, but, at that point, the context (this) becomes the outer one, I think, for I can access the variable 'mood' with 'this.mood' but I cannot access the inner context variables like '_currentStep'. If I try to do 'this._currentStep' the compiler says the _currentStep variable does not exist in the context of the page (and it is true). To access both information, I found finally a solution: 1) using an arrow function instead of function() let access to the outer context 2) variables of the inner context are contained inside this.introJsVar (look at my code to know what it is) so it is possibile to get the current step like this.introJsVar._currentStep