Created
December 17, 2011 05:41
-
-
Save hamakn/1489364 to your computer and use it in GitHub Desktop.
js2coffee sample http://js2coffee.org/ (javascript pattern observer sample)
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
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