Brightcove Player Sample: Custom Event

This topic shows you how to dispatch and listen for a custom event.

Overview

Even though the Brightcove player provides a number of out-of-the-box events, you may want to use your own custom events to decouple and eliminate dependencies between DOM objects and event listeners. This event-driven model is an architectural choice that you may want to consider. This sample adds a back button to the control bar. When the user clicks the back button, a custom event is triggered along with the amount of time to rewind. The custom event listener finds the current video position and rewinds the video.

Development sequence

Here is the recommended development sequence:

  1. Use the embed_in_page player implementation to test the functionality of your player, plugin and CSS (if CSS is needed)
  2. Put the plugin's JavaScript and CSS into separate files for local testing
  3. Deploy the plugin code and CSS to your server once you have worked out any errors
  4. Use Video CloudPerform Studio to add the plugin and CSS to your player
  5. Replace the embed_in_page player implementation if you determine that the iframe implementation is a better fit (detailed in next section)

For details about these steps, review the Quick Start to Plugin Development guide.

iframe or embed_in_page

When developing enhancements for the Brightcove player you will need to decide if the code is a best fit for the iframe or embed_in_page implementation. The best practice recommendation is to build a plugin for use with an iframe implementation. The advantages of using the iframe player are:

  • No collisions with existing JavaScript and/or CSS
  • Automatically responsive
  • The iframe eases use in social media apps (or whenever the video will need to "travel" into other apps)

Although integrating the embed_in_page player can be more complex, there are times when you will plan your code around that implementation. To generalize, this approach is best when the containing page needs to communicate to the player. Specifically, here are some examples:

  • Code in the containing page needs to listen for and act on player events
  • The player uses styles from the containing page
  • The iframe will cause application logic to fail, like a redirect from the containing page

Even if your final implementation does not use the iframe player, you can still use the embed_in_page player with a plugin that contains your JavaScript and CSS. This encapsulates your logic so that you can easily use it in multiple players.

Select implementation

This sample uses In-Page embed code to interact with page elements and trigger the custom rewind event. Plugin code is used in the player to listen for the custom event and rewind the video based on the data object in the event.

API resources used

The following sections detail resources used from various APIs.

Brightcove Player API methods

  • currentTime()

Brightcove Player API events

  • trigger
  • on

The player

Start video playback. Then click on the back button.

rewind video button

You should see that video playback goes back 5 seconds. Change the rewind amount to see how it affects how far the video goes back in time.

The following setting and message box are for demo purposes only, so that you can adjust the value:

Rewind video amount:

seconds.
Message Box

Event:

Position before rewind:

Position after rewind:


Understanding Custom events

Custom events allow you to decouple and eliminate dependencies between DOM objects and event listeners, creating an event-driven architectural model.

Dispatch

To dispatch a custom event, use the trigger() method as follows:

// trigger a custom event
myPlayer.trigger('eventName');
or
// trigger a custom event with data
myPlayer.trigger('eventName', {data: 'some data'});

For details about dispatching custom events, see the Player API index.

In this sample, the code does the following:

  • Dispatches a custom event, named rewind
  • Sends a data object with a name of amount and a value of 5 - You'll see in the JavaScript code where this value is set
// trigger a custom event with data
myPlayer.trigger('rewind', {'amount': rewindAmount});

Listen

To listen for a custom event, you can use the on() method as follows:

// listen for a custom event
player.on('eventName', function(evt){});
or
// listen for a custom event with data
player.on('eventName', function(evt,data){});

You can also use the one() method if you want the event listener to be triggered only once and then removed. For details about listening for events, see the Player API index.

In this sample, the code does the following:

  • Listens for a custom event, named rewind
  • Passes the event and data objects into a function
// listen for a custom event with data
 myPlayer.on('rewind',function(evt,data){
});

When you display the event and data objects in the console, it should look similar to this:

Custom event data
Custom event data

How it works

The following sections explain the player, JavaScript and CSS code used in the example.

Create the player

To create a player and assign a video to it, follow these steps:

  1. In the Players module, create a new player or use an existing one.
  2. In the Media module, select a video and publish it with this player.Assign video content to the player and publish it.
  3. Copy the In-Page embed code and paste it into a new HTML file.

    The embed code should look similar to this:

    <video id="video_1" style="width: 640px; height: 360px;"
    	data-video-id="4454629913001"
    	data-account="1752604059001"
    	data-player="default"
    	data-embed="default"
    	class="video-js"
    	controls></video>
    <script src="//players.brightcove.net/1752604059001/default_default/index.min.js"></script>
    <video id="video_1" style="width: 640px; height: 360px;"
    	data-account="1752604059001"
    	data-player="default"
    	data-embed="default"
    	class="video-js"
    	controls></video>
    <script src="//players.brightcove.net/1752604059001/default_default/index.min.js"></script>

The JavaScript code

The following code shows how we started with the custom event trigger and listener in the page code for testing.

  1. Add the following JavaScript to your page code:

    • Lines 38-50: Create the back/rewind button and place it in the spacer element of the control bar.
    • Line 50: Gets a reference to the new back button.
    • Lines 52-55: Use the trigger() method to dispatch the custom rewind event when the back button is clicked.
    • Lines 57-71: Use the on() method to listen for the custom rewind event. It then sets the video position back by the rewind amount passed through the event data object.

      <script type="text/javascript">
        videojs("video_1").ready(function() {
            // Create variables and new div and image elements for rewind icon
            var myPlayer = this,
                videoName,
    	    rewindAmount = 5,
                controlBar,
    	    newElement = document.createElement('div'),
    	    newImage = document.createElement('img');
    
            // Assign id to div for icon
            newElement.id = 'backButton';
    
            // Assign property to element and assign to parent
            newImage.setAttribute('src','http://solutions.brightcove.com/bcls/brightcove-player/custom-event/back-button.png');
            newElement.appendChild(newImage);
    
            // Get the spacer element
            spacer = document.getElementsByClassName('vjs-spacer')[0];
            // Place the new element in the spacer
            spacer.appendChild(newElement);
    
            backButton = document.getElementById("backButton");
    
            backButton.onclick = function() {
    	    // trigger a custom event with data
                myPlayer.trigger('rewind', {'amount': rewindAmount});
            }
    
            // listen for a custom event with data
            myPlayer.on('rewind',function(evt,data){
    
    	    var newTime,
    	        rewindAmt = data.amount,
    	        videoTime = myPlayer.currentTime();
    
    	    if (videoTime >= rewindAmt) {
    	        newTime = videoTime - rewindAmt;
    	    } else {
    	        newTime = 0;
    	    }
    
    	    myPlayer.currentTime(newTime);
            });
        });
      </script>

Use a plugin

It is a best practice to use a plugin so that you can easily add the JavaScript code's functionality to multiple players.

This sample leaves the function that dispatches the custom event in the page code. The custom event listener is added to the player as a plugin. This allows you to have several pages using this player, but only include the event dispatcher for those players where you want the rewind functionality.

Create the JavaScript file

Move the plugin's JavaScript code into a file and place it in an Internet accessible URL.

  1. Create a new file for your plugin JavaScript code. In this case, name it custom-event.js.
  2. Cut and paste the JavaScript code from your main HTML file into this new file.

    • Lines 1,20: Wrap your JavaScript code using the videojs.plugin() function. The first argument, customEventPlugin, is the plugin name.
    • Line 3: Gets a reference to your player.
    • The rest is your JavaScript code which was reviewed in a previous section.

    videojs.plugin('customEventPlugin', function() {
    
      var myPlayer = this;
    
      // listen for a custom event with data
      myPlayer.on('rewind',function(evt,data){
    
          var newTime,
          videoTime = myPlayer.currentTime(),
          rewindAmt = data.amount;
    
          if (videoTime >= rewindAmt) {
    	  newTime = videoTime - rewindAmt;
          } else {
    	  newTime = 0;
          }
    
          myPlayer.currentTime(newTime);
      });
    });
  3. In the HTML file, add the following code just below the existing <script> tags. This code includes the JavaScript file and then calls the method defined in that JavaScript.

    <script type="text/javascript" src="custom-event.js"></script>
    <script>videojs('video_1').customEventPlugin();</script>
  4. Browse the HTML page. You should see the rewind button, except now the custom event listener code has been removed from the HTML page.

Deploy plugin

To deploy the plugin using the Players module, follow these steps:

  1. In Video CloudPerform Studio, open the Players module and locate the player.
  2. Click the link for the player to open the player properties.
  3. Locate the Plugins section and click Edit.
  4. For the JavaScript URL, enter the URL which specifies the location of where you saved your plugin's JavaScript.
  5. For the CSS URL, enter the URL which specifies the location of where you saved your plugin's CSS.
  6. For the Name, enter customEventPlugin.
  7. There are no plugin options to enter.
    custom event plugin
  8. Click Save and then Publish the player.
  9. Browse the HTML page. You should see the rewind button, except now the custom event listener code has been added to your player.

Use iframe

It is a best practice to use the iframe player implementation. To do this, move all of the JavaScript code into the plugin for the player, publish the player and use the Standard Embed Code. Then, every page that uses this player will have a rewind button.