Skip to content

Instantly share code, notes, and snippets.

@cyjake
Last active October 14, 2015 02:25
Show Gist options
  • Save cyjake/9de829b28765e7a0d996 to your computer and use it in GitHub Desktop.
Save cyjake/9de829b28765e7a0d996 to your computer and use it in GitHub Desktop.
A simple event emitter mixin modified a bit from seajs
/*
* 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
}
}
@cyjake
Copy link
Author

cyjake commented Oct 14, 2015

原本抄到 oceanify/import.js 里了,现在发现用不到了,拷出来放在这里,方便以后用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment