event-target(设置事件)


Video.js中的事件的设置是为了模仿对象上使用的DOM API,也是具有相同功能的简短有用的函数。


on() and addEventListener()

此函数用于向EventTarget添加事件监听器。

var foo = new EventTarget();
var handleBar = function() {
  console.log('bar was triggered');
};

foo.on('bar', handleBar);

// This causes any `event listeners` for the `bar` event to get called
// see EventTarget#trigger for more information
foo.trigger('bar');
// logs 'bar was triggered'


off() and removeEventListener()

此函数用于从EventTarget中删除监听器函数。

var foo = new EventTarget();
var handleBar = function() {
  console.log('bar was triggered');
};

// adds an `event listener` for the `bar` event
// see EventTarget#on for more info
foo.on('bar', handleBar);

// runs all `event listeners` for the `bar` event
// see EventTarget#trigger for more info
foo.trigger('bar');
// logs 'bar was triggered'

foo.off('bar', handleBar);
foo.trigger('bar');
// does nothing


one()

此函数用于只调用一次事件监听器,而不会再次调用。

不推荐使用on()和off()达到one()的效果。

var foo = new EventTarget();
var handleBar = function() {
  console.log('bar was triggered');
  // after the first trigger remove this handler
  foo.off('bar', handleBar);
};

foo.on('bar', handleBar);
foo.trigger('bar');
// logs 'bar was triggered'

foo.trigger('bar');
// does nothing
使用one()
var foo = new EventTarget();
var handleBar = function() {
  console.log('bar was triggered');
};

// removed after the first trigger
foo.one('bar', handleBar);
foo.trigger('bar');
// logs 'bar was triggered'

foo.trigger('bar');
// does nothing


trigger() and dispatchEvent()

此函数用于触发EventTarget上的一个事件,该事件将会使所有监听器运行。

注意:如果‘click’在EventTarget.allowedEvents_中,触发器将尝试调用onClick函数(如果它存在)。

var foo = new EventTarget();
var handleBar = function() {
  console.log('bar was triggered');
};

foo.on('bar', handleBar);
foo.trigger('bar');
// logs 'bar was triggered'

foo.trigger('bar');
// logs 'bar was triggered'

foo.trigger('foo');
// does nothing


上一篇:embeds(引入) 下一篇:faq(常见问题)