在 Javascript 中制作我自己的事件投掷器

Crafting my own event thrower in Javascript

我知道(大部分)如何对生活在 DOM 中的那些物体引发的各种事件做出反应。

为了提高一点,我希望能够在适当的时候触发我自己的定制事件,我想我可以伪代码如下:

myObject = {
    prop:{ soAndSo }
    method : function(args){
        //do some stuff that takes forever
        "All done and ready, now tell the world"
    }
}

我的想法当然是在未来的某个时候我可以实例化一个 myObject,然后甚至在以后监视它的行为,达到

的效果
aMyObject.onmyevent = function(event){
    //do something appropriate for the circumstance
}

问题是,对于 "now tell the world" 部分,我不知道从哪里开始。

你能给我指明正确的方向吗?

您需要创建一个人造事件发射器。这是我在遵循 Pluralsight 的一个名为 React and Flux for Angular Developers 的教程时制作的: Tutorial

对于您的问题,您 'tell the world' 通过发出事件来调用您拥有的所有活动侦听器。

// make your own emitter:

function EventEmitter () {
  // holds events buy type; ex:'ADD_TODO'
  this._events = {};
}

EventEmitter.prototype.on = function(type, listener) {
  // add events to listen for
  this._events[type] = this._events[type] || [];
  this._events[type].push(listener);
};

EventEmitter.prototype.emit = function(type) {
  // emit event base on type
  if (this._events[type]) {
    this._event[type].forEach(function(listener) {
      // call listeners for events:
      listener();
    });
  }
};

EventEmitter.prototype.removeListener = function(type, listern) {
  if (this._events[type]) {
    this._events[type].splice(this._events[type].indexOf(listener), 1)
  }
};