Reputation: 172
I am using the Deezer Javascript SDK to play an audio track.
On their documentation there is a bunch of events defined such as player_loaded
, player_paused
, track_end
, etc.
They also show how subscribe to an event:
// Callback function is called when the current player has resumed or started playing
DZ.Event.subscribe('player_play', function(evt_name){
console.log("Player is playing");
});
// Callback function is called when the currently playing track has changed
DZ.Event.subscribe('current_track', function(track, evt_name){
console.log("Currently playing track", track);
});
// Callback function is called when the volume level of the current player has changed
DZ.Event.subscribe('volume_changed', function(args, evt_name){
console.log("The current volume level is " + args);
});
This works fine so far.
I was wondering if it is possible to access a variable from within the inner function:
DZ.Event.subscribe("track_end", function (evt_name) {
console.log("event fired 1");
//trying to access this bool var that is defined in data
this.isDeezerPlaying = false;
});
This is not working. I would have to pass in this
as a parameter to the callback function in order to access my local variable isDeezerPlaying
. But it is not me calling this function and passing the parameters but it is the SDK who does that somewhere under the hud.
So is there still a way?
Upvotes: 0
Views: 1385
Reputation: 14904
Yes you can. You either use arrow functions
DZ.Event.subscribe("track_end", (evt_name) => {
console.log("event fired 1");
//trying to access this bool var that is defined in data
this.isDeezerPlaying = false;
});
or you bind it:
DZ.Event.subscribe("track_end", function (evt_name) {
console.log("event fired 1");
//trying to access this bool var that is defined in data
this.isDeezerPlaying = false;
}.bind(this));
Upvotes: 3
Reputation: 3820
Yes you can by using arrow functions :
DZ.Event.subscribe("track_end", (evt_name) => {
console.log("event fired 1");
this.isDeezerPlaying = false;
});
How does the "this" keyword work?
https://stackoverflow.com/a/24900924/5671919
Upvotes: 1
Reputation: 1971
try with below code:
const vm = this;
DZ.Event.subscribe("track_end", function (evt_name) {
console.log("event fired 1");
//trying to access this bool var that is defined in data
vm.isDeezerPlaying = false;
});
Upvotes: 1