Event aggregation is also known as pubsub.
It deals message subscription and publication.
In both cases you work with a message key and you can publish or subscribe to be notified on the emitter found at crsbinding.events.emitter
.
Subscription can be seen as, "if anyone publishes a message using this key, please call this function for me."
crsbinding.events.emitter.on(eventKey, callback)
Once subscribed, you have to remember to remove the listener once you are done.
If you do not, you will have a memory leak.
crsbinding.events.emitter.remove(eventKey, callback)
You can have multiple objects listening for the same event key.
Publication takes on one of two forms.
- Implicit
- Targeted
Implicit uses a key, value pair and can be seen as, "if anyone is listening for this key, call the callback with this object as parameter".
Targeted is a bit different in that it's more direct, but we will deal with that one later.
Implicit publication uses the emit function.
crsbinding.events.emitter.emit(eventKey, argsObject)
Any subscribers on that key will called with the argsObject as parameter. Any object, be it a class, object or custom element can use implicit publishing.
Targeted publications do not work on a pull model but rather a push model.
The publication is done using the postMessage
function.
postMessage takes three parameters, two required and the last optional.
- query. css selector query on elements to target
- args. parmeters object that contains the details
- scope. what element to start the search on. if nothing provided this will be "document".
Because targeted uses css selectors you can only target custom elements.