Skip to content

Instantly share code, notes, and snippets.

@leohxj
Created January 31, 2018 03:18
Show Gist options
  • Save leohxj/e868ac580c692f4e815e1965414f59ae to your computer and use it in GitHub Desktop.
Save leohxj/e868ac580c692f4e815e1965414f59ae to your computer and use it in GitHub Desktop.
Events
class MyEvents {
constructor () {
this.events = {} //存储事件监听函数
this.maxListeners = 10 //一种函数类型,最大监听函数数量
}
setMaxListeners (maxNum) {
this.maxListeners = maxNum
}
getMaxListeners () {
return this.maxListeners
}
listeners (event) {
return this.events[event]
}
addListener (type, listener) {
if (this.events[type]) {
if (this.maxListeners != 0 && this.events[type].length > this.maxListeners) {
return console.error(`该${type}事件类型的listteners超出限制,使用emitter.setMaxListeners() 来增加添加事件监听数量。`)
}
this.events[type].push(listener)
} else {
this.events[type] = [listener]
}
}
once (type, listener) {
//执行后立即销毁
let wrapper = (...rest) => {
listener.apply(this, rest)
this.removeListener(type, wrapper)
}
this.addListener(type, wrapper)
}
removeListener (type, listener) {
if (this.events[type]) {
this.events[type] = this.events[type].filter(ev => {
ev != listener
})
//抛弃掉等于listener的
}
}
removeAllListener (type) {
delete this.events[type]
}
emit (type, ...rest) {
this.events[type] && this.events[type].forEach(listener => {
listener.apply(this, rest)
})
}
}
MyEvents.prototype.on = MyEvents.prototype.addListener
module.exports = MyEvents
作者:happyGloria
链接:https://juejin.im/post/5a6ebc056fb9a01ca072172b
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
@leohxj
Copy link
Author

leohxj commented Jan 31, 2018

var EventTarget = function() {
  this.listeners = {};
};

EventTarget.prototype.listeners = null;
EventTarget.prototype.addEventListener = function(type, callback) {
  if (!(type in this.listeners)) {
    this.listeners[type] = [];
  }
  this.listeners[type].push(callback);
};

EventTarget.prototype.removeEventListener = function(type, callback) {
  if (!(type in this.listeners)) {
    return;
  }
  var stack = this.listeners[type];
  for (var i = 0, l = stack.length; i < l; i++) {
    if (stack[i] === callback){
      stack.splice(i, 1);
      return;
    }
  }
};

EventTarget.prototype.dispatchEvent = function(event) {
  if (!(event.type in this.listeners)) {
    return true;
  }
  var stack = this.listeners[event.type];

  for (var i = 0, l = stack.length; i < l; i++) {
    stack[i].call(this, event);
  }
  return !event.defaultPrevented;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment