Event Target

Table of Contents

Overview

Events in Video.js are setup so that they mimic the DOM API that is used on object, but also have helpful shorthand functions with the same functionality.

on() and addEventListener()

This function is used to add an event listener to an EventTarget.

  1. var foo = new EventTarget();
  2. var handleBar = function() {
  3. console.log('bar was triggered');
  4. };
  5. foo.on('bar', handleBar);
  6. // This causes any `event listeners` for the `bar` event to get called
  7. // see EventTarget#trigger for more information
  8. foo.trigger('bar');
  9. // logs 'bar was triggered'

off() and removeEventListener()

This function is used to remove an listener function from an EventTarget.

  1. var foo = new EventTarget();
  2. var handleBar = function() {
  3. console.log('bar was triggered');
  4. };
  5. // adds an `event listener` for the `bar` event
  6. // see EventTarget#on for more info
  7. foo.on('bar', handleBar);
  8. // runs all `event listeners` for the `bar` event
  9. // see EventTarget#trigger for more info
  10. foo.trigger('bar');
  11. // logs 'bar was triggered'
  12. foo.off('bar', handleBar);
  13. foo.trigger('bar');
  14. // does nothing

one()

This function is used to only have an event listener called once and never again.

Using on() and off() to mimic one() (not recommended)

  1. var foo = new EventTarget();
  2. var handleBar = function() {
  3. console.log('bar was triggered');
  4. // after the first trigger remove this handler
  5. foo.off('bar', handleBar);
  6. };
  7. foo.on('bar', handleBar);
  8. foo.trigger('bar');
  9. // logs 'bar was triggered'
  10. foo.trigger('bar');
  11. // does nothing

Using one()

  1. var foo = new EventTarget();
  2. var handleBar = function() {
  3. console.log('bar was triggered');
  4. };
  5. // removed after the first trigger
  6. foo.one('bar', handleBar);
  7. foo.trigger('bar');
  8. // logs 'bar was triggered'
  9. foo.trigger('bar');
  10. // does nothing

trigger() and dispatchEvent()

This function is used to trigger an event on an EventTarget which will cause all listeners to run.

Note: if ‘click’ is in EventTarget.allowedEvents_, trigger will attempt to call the onClick function if it exists.

  1. var foo = new EventTarget();
  2. var handleBar = function() {
  3. console.log('bar was triggered');
  4. };
  5. foo.on('bar', handleBar);
  6. foo.trigger('bar');
  7. // logs 'bar was triggered'
  8. foo.trigger('bar');
  9. // logs 'bar was triggered'
  10. foo.trigger('foo');
  11. // does nothing