Created
February 2, 2012 15:54
-
-
Save joshkehn/1724128 to your computer and use it in GitHub Desktop.
Simple events in JavaScript vs. CoffeeScript
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 events, | |
__slice = Array.prototype.slice; | |
events = { | |
events: {}, | |
bind: function(topic, handler, context) { | |
var _base; | |
if (context == null) context = this; | |
return ((_base = this.events)[topic] || (_base[topic] = [])).push({ | |
handler: handler, | |
context: context | |
}); | |
}, | |
trigger: function() { | |
var args, event, topic, _i, _len, _ref, _results; | |
topic = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; | |
if (this.events[topic] != null) { | |
_ref = this.events[topic]; | |
_results = []; | |
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | |
event = _ref[_i]; | |
_results.push(event.handler.apply(event.context, args)); | |
} | |
return _results; | |
} | |
} | |
}; |
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 EventBinder = require('./events'), | |
e = new EventBinder(); | |
e.bind('hello', function (name) { | |
console.log('Hello', name); | |
}); | |
e.bind('hello', function (name) { | |
console.log('I just said "Hello" to', name); | |
}); | |
e.bind('goodbye', function (name) { | |
console.log('Goodbye', name); | |
}); | |
e.bind('goodbye', function (name) { | |
console.log('I just said "Goodbye" to', name); | |
}); | |
e.trigger('hello', 'Josh'); | |
e.trigger('goodbye', 'Josh'); |
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
function EventBinder () { | |
this.events = {}; | |
}; | |
EventBinder.prototype.bind = function bind (on, fn, context) { | |
if (!this.events[on]) { | |
this.events[on] = []; | |
} | |
context = context || this; | |
this.events[on].push({handler : fn, context : context}); | |
}; | |
EventBinder.prototype.trigger = function trigger (evt) { | |
var args = Array.prototype.slice.call(arguments).slice(1); | |
if (this.events[evt]) { | |
this.events[evt].forEach(function (caller) { | |
caller.handler.apply(caller.context, args); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment