I’m not entirely sure if there’s a better name for this pattern that already exists, but I like “handle pattern” to describe this method of keeping track of and managing “subscriptions”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
listen function that takes a “channel” and a callback function to call when that channel gets updated. The problem comes when you have to decide how to stop listening to that channel. If you go with a static
unlisten function on the publisher with the same signature as
listen (the channel and callback), you need to keep track of which callback is listening to which channel, and it can get messy.
listen can return a
handle, which is just an object that contains a method
unlisten that knows exactly how to stop listening on the specific channel and with the specific callback that was given to
listen. Then, the caller just needs to keep track of the return values of
listen (as opposed to the arguments to
listen) in order to be able to
The Dojo Stateful interface uses this pattern to watch values on objects. If you watch a property, a callback can be fired each time that property changes. The return value of
watch is a handle that can be used to stop watching that particular property value.
Feel free to play around with this code on JSFiddle.