Peers with multiple instances

7 views
Skip to first unread message

Max Antoni

unread,
Mar 19, 2011, 2:50:23 PM3/19/11
to hub.js
Singleton peers are created like this:

Hub.peer("namespace", {
/* ... */
});

Instead, a factory function can be provided to create mulitple peer
instances:

Hub.peer("namespace", function() {
return {
/* ... */
};
});

The interesting question is, when should an instance be created, how
is the lifecycle managed and how can it be referenced?

What currently happens is that an instance is created every time
someone calls Hub.publish("namespace/**") or anything that matches
this pattern. This happens regardless of whether the factory actually
produces a matching message function or not. It then registers the new
peer, attempts to invoke the addressed message(s) and the unregisters
the peer again.

This approach was a first draft and suffers from a number of problems.
The main problem is, that the new peer is created for each publish and
then garbage collected because nobody holds a reference to it.

The solutions that comes to my mind to create and reference peers:
1. A new method (e.g. Hub.createPeer) allows to explicitly create an
instance and returns an interface that allows to publish messages that
get picked up by that one instance.
2. The same as described in (1.) could be realized with Hub.publisher
and it would be transparent to users whether a new instance is
created, a singleton is used or any listener picks up the specified
topic.

In both cases the Hub should not hold any references to the returned
object so that it is garbage collected if the caller is not interested
in it anymore.

What would you prefer? Any other ideas?

Max Antoni

unread,
Mar 24, 2011, 6:38:44 PM3/24/11
to hub.js
This has been addressed in the last commit.
There is a new method Hub.get(namespace) that will create a new
instance of a prototype peer or always returns the same instance in
case of a singleton.
All methods are directly callable on the returned object and also
invoke all matching listeners on the Hub.
The Hub does not hold any references to the returned object if it is a
prototype, so the caller is responsible for storing the reference.

The corresponding test case can be found here:
https://github.com/mantoni/hub.js/blob/master/src-test/GetTest.js

A realistic use case is implemented in the Observer pattern test case:
https://github.com/mantoni/hub.js/blob/master/src-test/patterns/ObserverTest.js
Reply all
Reply to author
Forward
0 new messages