Skip to content

Commit 5e718d0

Browse files
committed
add event.js
1 parent d9c51c9 commit 5e718d0

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

events.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
function EventEmitter(){
2+
this._events = {};
3+
}
4+
5+
EventEmitter.prototype.on = function(eventName,callback){
6+
// if(eventName !== 'newListener'){
7+
// this._events['newListener'] ? this._events['newListener'].forEach(fn => fn(eventName)) : void 0
8+
// }
9+
if(!this._events){
10+
// this._events = {};这种方式有原型链
11+
this._events = Object.create(null);
12+
}
13+
if(this._events[eventName]){
14+
this._events[eventName].push(callback);
15+
}else{
16+
this._events[eventName] = [callback];
17+
}
18+
}
19+
20+
EventEmitter.prototype.once = function(eventName,callback){
21+
function one(){
22+
callback(...arguments);
23+
this.off(eventName,one);
24+
}
25+
one.link = callback;
26+
this.on(eventName,one);
27+
}
28+
29+
EventEmitter.prototype.off = function(eventName,callback){
30+
if(this._events[eventName]){
31+
this._events[eventName] = this._events[eventName].filter(fn => {
32+
fn != callback && fn.link != callback //为once做处理
33+
})
34+
}
35+
}
36+
37+
EventEmitter.prototype.emit = function(eventName){
38+
if(this._events[eventName]){
39+
this._events[eventName].forEach(fn => {
40+
fn.call(this,...arguments);
41+
});
42+
}
43+
}
44+
45+
module.exports = EventEmitter;

0 commit comments

Comments
 (0)