Created
April 8, 2014 14:17
-
-
Save madx/10131331 to your computer and use it in GitHub Desktop.
Simple Events as a functional mixin
This file contains hidden or 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
var hasEvents = (function() { | |
function on(name, callback, listener) { | |
var listener = listener || this | |
this._events = this._events || [] | |
this._events.push({ | |
name: name, | |
callback: callback, | |
listener: listener | |
}) | |
} | |
function off(name, listener) { | |
var listener = listener || this | |
this._events = this._events || [] | |
this._events = this._events.filter(function(event) { | |
console.log([event.listener === listener, event.name === name]) | |
return event.listener !== listener || event.name !== name | |
}) | |
} | |
function listenTo(target, name, callback) { | |
var self = this | |
target.on(name, function() { | |
callback.apply(self, arguments) | |
}, this) | |
} | |
function stopListening(target, name) { | |
target.off(name, this) | |
} | |
function trigger(name) { | |
var self = this | |
var args = Array.prototype.slice.call(arguments, 1) | |
this._events = this._events || [] | |
this._events.forEach(function(event) { | |
if (event.name === name) { | |
setTimeout(function() { | |
event.callback.apply(self, args) | |
}, 0) | |
} | |
}) | |
} | |
return function() { | |
this.on = on | |
this.off = off | |
this.listenTo = listenTo | |
this.stopListening = stopListening | |
this.trigger = trigger | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment