-
-
Save ryanflorence/2382307 to your computer and use it in GitHub Desktop.
@events = | |
events: {} | |
on: (topic, handler, context = this) -> | |
(@events[topic] or= []).push {handler, context} | |
trigger: (topic, args...) -> | |
return unless @events[topic]? | |
handler.apply(context, args) for {handler, context} in @events[topic] |
(function() { | |
var slice = Array.prototype.slice; | |
this.events = { | |
events: {}, | |
on: function (topic, handler, context) { | |
if (context == null) context = this; | |
this.events[topic] = this.events[topic] || [] | |
this.events[topic].push({ handler: handler, context: context }); | |
}, | |
trigger: function (topic) { | |
if (this.events[topic] == null) return; | |
var args = slice.apply(arguments, 1); | |
for (var i = 0, l = this.events[topic].length, event; i < l; i++) { | |
event = this.events[topic][i]; | |
event.handler.apply(event.context, args); | |
} | |
} | |
}; | |
}).call(this); |
I've personally always found return unless
confusing -- my brain always has to stop and think hard about what it means, kind of like a double negative. (Since it makes it seem like the default is to return, so in what case do I continue?)
I find return if not
clearer in those cases. Just my two cents. =) Fantastic video though!
Destructured assignment in a for ... in looks awesome, thanks for the example.
One small issue: trigger
is now going to collect the return values of handler
. Add an undefined
or null
as the last expression of trigger
.
It would be better to add return
statement, so methods will return nothing. If we add undefined
or null
the methods will contain return undefined
or return null
in their JavaScript presentation.
Something like this would be more correct (like source JS code)
@events =
events: {}
on: (topic, handler, context = this) ->
(@events[topic] or= []).push {handler, context}; return
trigger: (topic, args...) ->
return unless @events[topic]?
handler.apply(context, args) for {handler, context} in @events[topic]; return
Yeah, I'm well aware of implicit returns guys; I'd return this
if I cared, but don't :)
Code from the article: Rewriting Some JavaScript to CoffeeScript