Hello,
maybe you could help me. Currently I’m rewriting our JS-Videoplayer with Stimulus.
I got a problem which I can’t fix.
Here some code, to explain my problem:
export default class extends Controller {
static targets = [
"playerContainer",
];
connect() {
const container = this.playerContainerTarget;
this.buildPlayerUI(); // initializes the player and sets the `App.bitmovinPlayer` variable.
App.bitmovinPlayer.on(PlayerEvent.Ready, function (event) {
this.reloadScriptTab();
}
}
}
The this.reloadScriptTab()
does not work, because in this Scope this
is set Bitmovin.
Do you have a solution to get the this
-variable back or the function working?
Thank you very much!
The “classic” way to solve this problem, before fat-arrow syntax, would be to define another variable, like self
that points to the appropriate this
:
connect() {
var self = this; // The binding you're looking for.
App.bitmovinPlayer.on(PlayerEvent.Ready, function (event) {
self.reloadScriptTab();
}
}
That said, with more modern code, you might just be able to use fat-arrows to maintain this
binding:
connect() {
const container = this.playerContainerTarget;
this.buildPlayerUI();
// Using FAT-ARROW syntax to maintain `this` binding.
App.bitmovinPlayer.on(PlayerEvent.Ready, (event) => {
this.reloadScriptTab();
}
}
It comes down, a bit, to whether or not you need to access Bitmovin
inside your event-handler?
Thank you very much, my problem is fixed! Sorry for the newbie question.
1 Like
Awesome! Glad that worked out! We’re all newbies at something, that’s what community is for