@@ -12,33 +12,36 @@ You have to notify some objects about an event happen
12
12
Use an [ Observer Pattern] ( http://en.wikipedia.org/wiki/Observer_pattern )
13
13
14
14
{% highlight coffeescript %}
15
+
15
16
class PostOffice
16
- constructor: () ->
17
- @subscribers = [ ]
18
- sendNewItemReleased : (item) ->
19
- subscriber.callback(item) for subscriber in @subscribers when subscriber.item is item
20
- return
21
- subscribe: ( to, onNewItemReleased) ->
22
- @ subscribers .push({'item' : to , 'callback' : onNewItemReleased })
17
+ constructor: () ->
18
+ @subscribers = [ ]
19
+ notifyNewItemReleased : (item) ->
20
+ subscriber.callback(item) for subscriber in @subscribers when subscriber.item is item
21
+ subscribe: (to, onNewItemReleased) ->
22
+ @ subscribers .push {'item' : to , 'callback' : onNewItemReleased }
23
+
23
24
class MagazineSubscriber
24
- onNewMagazine: (item) ->
25
- alert "I've got new "+item
25
+ onNewMagazine: (item) ->
26
+ alert "I've got new "+item
27
+
26
28
class NewspaperSubscriber
27
- onNewNewspaper: (item) ->
28
- alert "I've got new "+item
29
+ onNewNewspaper: (item) ->
30
+ alert "I've got new "+item
29
31
30
32
postOffice = new PostOffice()
31
33
sub1 = new MagazineSubscriber()
32
34
sub2 = new NewspaperSubscriber()
33
35
postOffice.subscribe "Mens Health", sub1.onNewMagazine
34
36
postOffice.subscribe "Times", sub2.onNewNewspaper
35
- postOffice.sendNewItemReleased "Times"
36
- postOffice.sendNewItemReleased "Mens Health"
37
+ postOffice.notifyNewItemReleased "Times"
38
+ postOffice.notifyNewItemReleased "Mens Health"
39
+
37
40
{% endhighlight %}
38
41
39
42
## Discussion
40
43
41
44
Here you have an observer object (PostOffice) and observable objects (MagazineSubscriber, NewspaperSubscriber).
42
45
To be notified about an event of publishing new periodical observable object should make subscribtion on PostOffice.
43
- Every of subscribed objects is stored internaly in the PostOffice array of subscribers .
46
+ Every of subscribed objects is stored internaly in the PostOffice array of subscribtions .
44
47
Every subscriber is notified on new concrete periodical is published.
0 commit comments