Skip to content

Instantly share code, notes, and snippets.

@jtompkins
Created February 17, 2014 19:39
Show Gist options
  • Save jtompkins/9057458 to your computer and use it in GitHub Desktop.
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.
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]
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