我可以很好地添加一些事件。
addEventListener("onStateChange", "handleStateChange");但是,当试图删除事件时,它不会。
removeEventListener("onStateChange", "handleStateChange");每当我暂停/播放视频时,仍会调用handleStateChange。有没有人遇到这样的问题并有解决办法?或者API上有bug?
发布于 2014-09-19 07:15:57
我认为问题在于,YouTube API的player对象没有removeEventListener方法。请记住,当您调用addEventListener时,您这样做是作为构建的youtube player对象的一种方法,而不是使用定义为DOM元素方法的方法( YouTube API选择将它们的方法命名为相同的方法以使开发人员更加熟悉)。
过去对其他人有用的一个建议是,当您处于可能需要删除事件侦听器的情况下,只需重新定义状态更改回调.类似于:
handleStateChange = function() {};发布于 2018-08-05 05:28:17
对于我的应用程序来说,这已经够麻烦了,以至于我为YouTube player对象做了一种事件发射代理。
使用(其中player是YouTube Iframe实例):
const playerEventProxy = new YouTubeEventProxy(player);
function handleStateChange(e) {
// …
}
playerEventProxy.on('stateChange', handleStateChange);
playerEventProxy.off('stateChange', handleStateChange);类:
/**
* YouTubeEventProxy
* Quick and dirty hack around broken event handling in the YouTube Iframe API.
* Events are renamed, dropping the "on" and lower-casing the first character.
* Methods 'on', 'off', etc. are supported, as-provided by event-emitter.
* See also: https://stackoverflow.com/q/25880573/362536
*
* Brad Isbell <brad@audiopump.co>
* License: MIT <https://opensource.org/licenses/MIT>
*/
import EventEmitter from 'event-emitter';
// From: https://developers.google.com/youtube/iframe_api_reference#Events
const ytApiEvents = [
'onApiChange',
'onError',
'onPlaybackQualityChange',
'onPlaybackRateChange',
'onReady',
'onStateChange'
];
export default class YouTubeEventProxy extends EventEmitter {
constructor(player) {
super();
this.player = player;
ytApiEvents.forEach((eventName) => {
player.addEventListener(
eventName,
this.emit.bind(
this,
eventName.substr(2, 1).toLowerCase() + eventName.substr(3)
)
);
});
}
}这是event-emitter包:https://www.npmjs.com/package/event-emitter
https://stackoverflow.com/questions/25880573
复制相似问题