Created
February 17, 2014 19:39
-
-
Save jtompkins/9057458 to your computer and use it in GitHub Desktop.
A simple message dispatcher in Coffeescript. This is a very naive implementation and probably doesn't do everything you'd want a message dispatcher to do. On the other hand, it's under 30 lines of code.
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
class Messenger | |
constructor: -> | |
@subs = {} | |
register: (type, caller, func) => | |
return unless type? and caller? and func? | |
@subs[type] = [] unless @subs[type]? | |
existing = null | |
for s in @subs[type] | |
if s.caller is caller and s.func is func | |
existing = s | |
break | |
@subs[type].push { caller: caller, func: func } unless existing? | |
unregister: (type, caller) => | |
return unless @subs[type]? and caller? | |
@subs[type] = (s for s in @subs[type] when s.caller isnt caller) | |
send: (type, params...) => | |
return unless @subs[type]? | |
sub.func params... for sub in @subs[type] |
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
var messenger = new Messenger(); | |
//register to receive the refresh message | |
//normally, 'this' would be a view model or other object | |
messenger.register("refresh", this, this.refresh); | |
//now send the message every 60 seconds | |
window.setInterval(function() { messenger.send("refresh"); }, 60000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment