observer
={addSubscriber:function(callback)
{this.
subscribers[
this.
subscribers.
length]
=callback
;},removeSubscriber:function(callback)
{for(
vari
=0;i
<this.
subscribers.
length;i
++)
{if(
this.
subscribers[i]
===callback)
{delete(
this.
subscribers[i])
;}}},publish:function(what)
{for(
vari
=0;i
<this.
subscribers.
length;i
++)
{if(
typeofthis.
subscribers[i]
==='function')
{this.
subscribers[i](what)
;}}},make:function(o)
{// turns an object into a publisherfor(
vari
inthis)
{o[i]
=this[i]
;o.
subscribers=[]
;}}};varblogger
={writeBlogPost:function()
{varcontent
='Today is '+newDate()
;this.
publish(content)
;}};varla_times
={newIssue:function()
{varpaper
='Martians have landed on Earth!';this.
publish(paper)
;}};observer.
make(blogger)
;observer.
make(la_times)
;varjack
={read:function(what)
{console.
log(
'I just read that '+what)
}};varjill
={gossip:function(what)
{console.
log(
'You didn\'t hear it from me, but '+what)
}};blogger.
addSubscriber(
jack.
read)
;blogger.
addSubscriber(
jill.
gossip)
;blogger.
writeBlogPost()
;blogger.
removeSubscriber(
jill.
gossip)
;blogger.
writeBlogPost()
;la_times.
addSubscriber(
jill.
gossip)
;la_times.
newIssue()
;来源: http://www.cnblogs.com/avilang/p/6881836.html