Skip to content

Instantly share code, notes, and snippets.

@hamakn
Created December 17, 2011 05:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamakn/1489364 to your computer and use it in GitHub Desktop.
Save hamakn/1489364 to your computer and use it in GitHub Desktop.
js2coffee sample http://js2coffee.org/ (javascript pattern observer sample)
makePublisher = (o) ->
i = undefined
for i of publisher
o[i] = publisher[i] if publisher.hasOwnProperty(i) and typeof publisher[i] is "function"
o.subscribers = any: []
publisher =
subscribers:
any: []
subscribe: (fn, type) ->
type = type or "any"
@subscribers[type] = [] if typeof @subscribers[type] is "undefined"
@subscribers[type].push fn
unsubscribe: (fn, type) ->
@visitSubscribers "unsubscribe", fn, type
publish: (publication, type) ->
@visitSubscribers "publish", publication, type
visitSubscribers: (action, arg, type) ->
pubtype = type or "any"
subscribers = @subscribers[pubtype]
i = undefined
max = subscribers.length
i = 0
while i < max
if action is "publish"
subscribers[i] arg
else
subscribers.splice i, 1 if subscribers[i] is arg
i += 1
paper =
daily: ->
@publish "big news today"
monthly: ->
@publish "interesting analysis", "monthly"
makePublisher paper
joe =
drinkCoffee: (paper) ->
console.log "Just read " + paper
sundayPreNap: (monthly) ->
console.log "About to fall asleep reading this " + monthly
paper.subscribe joe.drinkCoffee
paper.subscribe joe.sundayPreNap, "monthly"
paper.daily()
paper.daily()
paper.daily()
paper.monthly()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment