# EventEmit
代码语言:javascript复制export default class EventEmitter {
constructor () {
this.events = {};
this.maxListeners = 10;
}
on (eventName, listener) {
if (this.events[eventName]) {
if (this.events[eventName].length >= this.maxListeners) {
console.warn(`EventEmitter: maxListeners exceeded.`);
return;
}
this.events[eventName].push(listener);
} else {
this.events[eventName] = [];
this.events[eventName].push(listener);
}
}
emit (eventName, ...rest) {
if (this.events[eventName]) {
this.events[eventName].map(fn => fn.apply(this, rest));
}
}
removeListener (eventName, listener) {
if (this.events[eventName]) {
delete this.events[eventName];
}
}
removeAllListeners () {
this.events = {};
}
}
使用
代码语言:javascript复制import EventEmit from './EventEmit';
let DeviceEventEmitter = new EventEmit();
DeviceEventEmitter.on('event', (param1, param2) => {
console.log(param1, param2);
});
DeviceEventEmitter.emit('event', 'param1', 'param2'); // param1 param2
DeviceEventEmitter.removeListener('event');
# EventBus
代码语言:javascript复制class EventBus {
constructor () {
this.events = this.events || {};
}
$on (eventName, callback) {
if (this.events[eventName]) {
this.events[eventName].push(callback);
} else {
this.events[eventName] = [];
this.events[eventName].push(callback);
}
}
$emit (eventName, ...rest) {
if (this.events[eventName]) {
this.events[eventName].map(fn => fn.apply(this, rest));
}
}
$once (eventName, callback) {
const self = this;
const onceCallback = function () {
callback.apply(self, arguments);
self.$off(eventName);
};
this.$on(eventName, onceCallback);
}
$off (eventName) {
if (eventName) {
if (this.events[eventName]) {
delete this.events[eventName];
}
} else {
this.events = {};
}
}
}