Last active
October 14, 2015 02:25
-
-
Save cyjake/9de829b28765e7a0d996 to your computer and use it in GitHub Desktop.
A simple event emitter mixin modified a bit from seajs
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
/* | |
* EventEmitter from seajs | |
*/ | |
var EventEmitter = { | |
// Bind event | |
on: function(name, callback) { | |
var events = this.events | |
var list = events[name] || (events[name] = []) | |
list.push(callback) | |
return this | |
}, | |
// Remove event. If `callback` is undefined, remove all callbacks for the | |
// event. If `event` and `callback` are both undefined, remove all callbacks | |
// for all events | |
off: function(name, callback) { | |
// Remove *all* events | |
if (!(name || callback)) { | |
this.events = {} | |
return this | |
} | |
var events = this.events | |
var list = events[name] | |
if (list) { | |
if (callback) { | |
for (var i = list.length - 1; i >= 0; i--) { | |
if (list[i] === callback) { | |
list.splice(i, 1) | |
} | |
} | |
} | |
else { | |
delete events[name] | |
} | |
} | |
return this | |
}, | |
// Emit event, firing all bound callbacks. Callbacks receive the same | |
// arguments as `emit` does, apart from the event name | |
emit: function(name, data) { | |
var list = this.events[name] | |
if (list) { | |
// Copy callback lists to prevent modification | |
list = list.slice() | |
// Execute event callbacks, use index because it's the faster. | |
for(var i = 0, len = list.length; i < len; i++) { | |
list[i](data) | |
} | |
} | |
return this | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
原本抄到 oceanify/import.js 里了,现在发现用不到了,拷出来放在这里,方便以后用