Reputation: 16705
I'm trying to use the YouTube API to control several you-tube videos. And I'm following the google code example. But the problem is that they require a global string for their listener callback.
ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
where ytplayer
is the "object" element that contains the flash video player. Following their example it seems I need to create a new global function for each player -- onPlayerStateChange2
, etc. They don't allow function references (anonymous or otherwise) in place of the string, and locally defined strings don't work either. How can I avoid explicitly named global functions? The following works
var localStateChangeHandler = function (newState) {
updateHTML("playerState", newState);
}
var globalStateChangeString = 'onPlayerStateChange'+ytplayer.id;
eval(globalStateChangeString + ' = localStateChangeHandler');
ytplayer.addEventListener("onStateChange", globalStateChangeString);
but it's not very pretty, it's still creating global functions, and is using an "eval". Is there a better way?
Upvotes: 1
Views: 618
Reputation: 141889
You could encapsulate it inside a single object and use currying to hide multiple global functions. Let's say you have a global object and with a dispatchEvent method on it.
Player = {};
Player.dispatchEvent = function(id) {
var player = document.getElementById(id);
return function(newState) {
console.log("player id %s changed state to %s", id, newState);
};
};
Then add a call to dispatchEvent as a string with the correct id, when adding the state change event listener.
var call = 'Player.dispatchEvent("{id}")'.replace("{id}", somePlayerId);
ytplayer.addEventListener('onStateChange', call);
When the string is eval'd by Youtube, it would return a reference to an anonymous function that holds the player id through a closure, and receives the state change parameter in the next invocation.
I have written a small class YoutubePlayer, inspired by this blog article, to play multiple videos and handle events from each one of them separately while keeping the global state minimal, which you might find useful.
Upvotes: 3