Created
April 7, 2015 15:00
-
-
Save Williammer/e798f376108734204614 to your computer and use it in GitHub Desktop.
example of observer pattern.
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
"use strict"; | |
var publisher = { | |
subscribers: { | |
any: [] // event type: subscribers | |
}, | |
subscribe: function (fn, type) { | |
type = type || 'any'; | |
if (typeof this.subscribers[type] === "undefined") { | |
this.subscribers[type] = []; | |
} | |
this.subscribers[type].push(fn); | |
}, | |
unsubscribe: function (fn, type) { | |
this.visitSubscribers('unsubscribe', fn, type); | |
}, | |
publish: function (publication, type) { | |
this.visitSubscribers('publish', publication, type); | |
}, | |
visitSubscribers: function (action, arg, type) { | |
var pubtype = type || 'any', | |
subscribers = this.subscribers[pubtype], | |
i, | |
max = subscribers.length; | |
for (i = 0; i < max; i += 1) { | |
if (action === 'publish') { | |
subscribers[i](arg); | |
} else { | |
if (subscribers[i] === arg) { | |
subscribers.splice(i, 1); | |
} | |
} | |
} | |
} | |
}; | |
/* | |
var s1 = {log: console.log}, | |
s2 = {err: console.error}, | |
s3 = {warn: console.warn}; | |
publisher.subscribe(s1.log); | |
publisher.subscribe(s2.err); | |
publisher.subscribe(s3.warn); | |
publisher.publish({hello: "World"}); | |
publisher.unsubscribe(s2.err); | |
publisher.publish("hello"); | |
publisher.subscribe(s1.log, "log"); | |
publisher.publish({obj: "log this object"}, "log"); | |
*/ | |
function makePublisher(o) { | |
var i; | |
for (i in publisher) { | |
if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") { | |
o[i] = publisher[i]; | |
} | |
} | |
o.subscribers = {any: []}; | |
} | |
var paper = { | |
daily: function () { | |
this.publish("big news today"); | |
}, | |
monthly: function () { | |
this.publish("interesting analysis", "monthly"); | |
} | |
}; | |
makePublisher(paper); | |
var joe = { | |
drinkCoffee: function (paper) { | |
console.log('Just read ' + paper); | |
}, | |
sundayPreNap: function (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(); | |
makePublisher(joe); | |
joe.tweet = function (msg) { | |
this.publish(msg); | |
}; | |
paper.readTweets = function (tweet) { | |
alert('Call big meeting! Someone ' + tweet); | |
}; | |
joe.subscribe(paper.readTweets); | |
joe.tweet("hated the paper today"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment