js 如何用 on 监听方法

我有如下一个Player,想在实例上用on监听,并在两秒后触发 opened 方法, 请教各位大佬

class Player {
    constructor(arg) {
        setTimeout(() => {
            //这里两秒后触发 opened 方法不知道怎么写了。。。
        }, 2000)
    }
    on(key, callback) {

    }
}
let player = new Player();
player.on('opened', function(data) {
    console.log(data)
})
阅读 3.3k
1 个回答

你的目的是想实现类似js事件监听那样的效果么

  • 给对应事件注册指定的处理函数
  • 触发事件
  • 执行事件处理函数

如果是这样的话.要分三个步骤

  • 定义好事件常量
  • 订阅事件
  • 触发事件

-

class Player {
  KEY_LIST = ['opened'];
  opendFunc = [];
  constructor() {
  const self = this;
    setTimeout(function () {
      self.opened();
    }, 1234);
  }
  on (key, callback) {
     if (!this.KEY_LIST.includes(key)) {
       console.error('the key is not occured in the list');
       return;
     }
     if (typeof callback !== 'function') {
       console.error('the callback must be a function');
       return;
     }
     // 用数组可以保证传入多个事件处理函数
     this.opendFunc.push(callback);
  }
  opened () {
    this.opendFunc.forEach(func => func(this));
  }
}

const player = new Player();

player.on('opened', function (e) {
  console.log(e);
})
// 可以在任意的地方触发事件
player.opened();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题