[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

event listener, objects and this

pentapus

10/21/2014 1:33:00 AM

I'm writing an object for an HTML5 audio player

in my object initialization code I have this:

function audioVideoPlayer(id){
this.id = id;
this.playing = false;
this.endOfTrack = endOfTrack;
....

this.player.addEventListener("ended",this.endOfTrack);

That calls the endOfTrack function but the endOfTrack function believes
"this" refers to the audio element, not to the object I wrote. How do I
properly call the endOfTrack method?

Nice to see this group is still kicking and doing good work.


--
pentapus
1 Answer

JJ

10/21/2014 6:41:00 AM

0

On Mon, 20 Oct 2014 21:33:23 -0400, pentapus wrote:
> I'm writing an object for an HTML5 audio player
>
> in my object initialization code I have this:
>
> function audioVideoPlayer(id){
> this.id = id;
> this.playing = false;
> this.endOfTrack = endOfTrack;
> ...
>
> this.player.addEventListener("ended",this.endOfTrack);
>
> That calls the endOfTrack function but the endOfTrack function believes
> "this" refers to the audio element, not to the object I wrote. How do I
> properly call the endOfTrack method?
>
> Nice to see this group is still kicking and doing good work.

Use a bound event handler.

this.player.addEventListener("ended", this.endOfTrack.bind(this));

Assuming that "this" in that context, is the object you want.