Logo-small

3.1.2 Subscribing and reacting to events as a Client

Here is an example taken from Ramon Leon's very good Smalltalk blog. This example shows how we can use announcements to manage the communication between a parent component and its children as for example in the context of a menu and its menu items.

Two straightforward steps are necessary to set up a client to react to some events:

  1. retrieving a reference to the announcer of your subject
  2. registering an action in response to some events of the announcer

This is illustrated by the following line of code: the announcer is retrieved through an accessor and #on:do: is sent to the announcer to register interest in RemoveChild events. Consequently, the action block takes as parameter an instance of RemoveChild event class.

Parent>>initialize
super initialize.
self session announcer on: RemoveChild do: [:it | self removeChild: it child]
Parent>>removeChild: aChild
self children remove: aChild

If you want to register the same action for multiple events, simply create an AnnouncementSet using a comma:

Parent>>initialize
super initialize.
self session announcer on: AddChild, RemoveChild do: [:it | self changeChild: it child]

If your client object is to be destroyed before the subject, do not forget to unsubscribe it from the announcer, or it will not be garbage collected and will keep receiving events!

Parent>>delete
self session announcer unsubscribe: self

User Contributed Notes

sebnozzi (12 November 2012, 2:50 pm)

The way to make a "weak" subscription is as follows: when you pass "on:to:" to the "Announcer", you get an "AnnouncementSubscription" back. You'd need to pass "makeWeak" to it.

 

From the documentation of "WeakAnnouncementSubscription":

 

"To switch between subscription types, use makeStrong/makeWeak on the subscription returned when initially registering with announcer."

 

BUT ... it's not currently supported!! :-(

 

"No support for ephemerons currently prevents this from working for Block actions (blocks hold their receiver, which is the default subscriber strongly)."

 

What is an ephemeron?

 

http://lists.gforge.inria.fr/pipermail/pharo-project/2011-May/049402.html

 

Sebastian Nozzi

simon.denier (7 January 2011, 3:01 am)

Certainly, but what's the status of weak references in Pharo? I always heard they were kind of buggy.

sean (1 January 2011, 6:23 pm)

Wouldn't it be better/more robust to use weak references so you don't leak if you forget to manually unsubscribe?

 

Sean DeNigris

Add a Note

Licensed under Creative Commons BY-NC-SA | Published using Pier |