Skip to content
Advertisement

Get callback in CoffeeScript with library

I am using the YouTube API to embed a video on a page. I call swfobject.embedSWF which embeds the video on the page, it works. When it is done loading, the API is supposed to call onYouTubePlayerReady. My question though is where do I have to place the callback in my class to get the function called?

Here is the code that I have tried, but that does not work.

class YouTube

    constructor: (@uid) ->
        youtube_video_container =   $('<div/>', {
              id: 'ytapiplayer'
        }).appendTo(main);

        params = { allowScriptAccess: "always" };
        atts = { id: "myytplayer" };

        swfobject.embedSWF("http://www.youtube.com/apiplayer?video_id=d9NF2edxy-M&version=3&enablejsapi=1", "ytapiplayer", "1280", "720", "8", null, null, params, atts);

    onYouTubePlayerReady: (playerId) ->
           alert "ready"

Advertisement

Answer

From the fine manual:

In addition, any HTML page that contains the YouTube player must implement a JavaScript function named onYouTubePlayerReady. The API will call this function when the player is fully loaded and the API is ready to receive calls.

and onYouTubePlayerReady:

onYouTubePlayerReady(playerid)

Called when the player is fully loaded and the API is ready to receive calls. If a playerapiid is passed into the player via URL arguments, then it will be passed to this function.

So if you include &playerapiid=X in the URL’s CGI parameters, then that X will be the playerid when onYouTubePlayerReady is called.

All of that indicates that onYouTubePlayerReady is a global function rather than a method on an object of your choice or a callback that you can specify as you please. To make a global function with CoffeeScript, create a property on window:

window.onYouTubePlayerReady = (playerid) ->
    alert 'Ready'

You’d have to use the playerid to backtrack to the specific object that created the player through some globally accessible playerid-to-object map.

Even the addEventListener interface is based on names rather than callbacks so you’re stuck polluting the global namespace and routing things yourself.

Advertisement