W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
當(dāng)一個事件發(fā)生時你不得不向一些對象發(fā)布公告。
使用觀察者模式(Observer Pattern)。
class PostOffice
constructor: () ->
@subscribers = []
notifyNewItemReleased: (item) ->
subscriber.callback(item) for subscriber in @subscribers when subscriber.item is item
subscribe: (to, onNewItemReleased) ->
@subscribers.push {'item':to, 'callback':onNewItemReleased}
class MagazineSubscriber
onNewMagazine: (item) ->
alert "I've got new "+item
class NewspaperSubscriber
onNewNewspaper: (item) ->
alert "I've got new "+item
postOffice = new PostOffice()
sub1 = new MagazineSubscriber()
sub2 = new NewspaperSubscriber()
postOffice.subscribe "Mens Health", sub1.onNewMagazine
postOffice.subscribe "Times", sub2.onNewNewspaper
postOffice.notifyNewItemReleased "Times"
postOffice.notifyNewItemReleased "Mens Health"
這里你有一個觀察者對象(PostOffice)和可觀察對象(MagazineSubscriber, NewspaperSubscriber)。為了通報(bào)發(fā)布新的周期性可觀察對象的事件,應(yīng)該對 PostOffice進(jìn)行訂閱。每一個被訂閱的對象都存儲在PostOffice的內(nèi)部訂閱數(shù)組中。當(dāng)新的實(shí)體周期發(fā)布時每一個訂閱者都會收到通知。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: