File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ;
You can’t perform that action at this time.
0 commit comments