Last active
May 22, 2019 11:20
-
-
Save LeeeeeeM/21f51562c6d7f3cf14a52dea42275e49 to your computer and use it in GitHub Desktop.
Event实现trigger、on、off、once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Event() { | |
this.fnMap = {}; | |
} | |
Event.prototype.on = function(type, fn) { | |
var fns = this.fnMap[type] || (this.fnMap[type] = []) | |
fns.push(fn); | |
return this; | |
}; | |
Event.prototype.off = function(type, fn) { | |
var fns = this.fnMap[type]; | |
if (fns) { | |
for (var i = fns.length; i >= 0; --i) { | |
if (fns[i] === fn) { | |
fns.splice(i, 1); | |
} | |
} | |
} | |
return this; | |
}; | |
Event.prototype.trigger = function(type, data) { | |
var fns = this.fnMap[type]; | |
if (fns) { | |
for (var i = 0; i < fns.length; i++) { | |
fns[i].call(this, data); | |
} | |
} | |
}; | |
Event.prototype.once = function(type, fn) { | |
var fns = this.fnMap[type] || (this.fnMap[type] = []) | |
var self = this; | |
var wrapper = function() { | |
fn.apply(self, arguments); | |
self.off(type, wrapper); | |
}; | |
fns.push(wrapper); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
今天重新写了个EventEmitter,发现了错误。
emit的时候,需要将数组slice出来,否则会干扰emit的时候的数组长度,导致错误。