Leveraging Publish and Subscribe
Key Points
- Use
Events.includeIn(obj);to add events into any object. - Events have been added to the app module by default, to support app-wide messaging.
- Use
trigger(eventList, payload)to publish a message. - Use
on(eventList).then(...)to subscribe to a message. :::
Adding Events to An Object
You can add events to any object by using the events module. Here's how you would do it:
var Events = require('durandal/events');
var myObj = { ... };
Events.includeIn(myObj);
By doing this, myObj gains the following functions:
on- Subscribe to this object's events.off- Un-subscribe to this object's events.trigger- Trigger this object's events.proxy- Proxy this object's events.
You can pass the all event name to subscribe to all events.
You can see the events module reference documentation for more detailed information on these. Some examples of using the app module's events are demonstrated below.
The eventList that is passed to the functions above can be a list of events to publish or subscribe to. Whitespace is used to delimit events. :::
Using Application-Wide Messaging
By default, the app module has already had the events capability added to it. This sets you up to do application-wide messaging out-of-the-box. In light of that, here are a few simple use cases:
Publishing an app-wide message.
app.trigger("customer:new", newCustomer);
Subscribing to an app-wide message.
app.on("customer:new").then(function (customer) {
//do something with the payload
});
Subscribing to all app-wide messages.
app.on("all").then(function (event) {
//the arguments array contains the payload
});
Un-subscribing from an app-wide message.
var subscription = app.on('customer:new').then(function(customer){
//do something with the payload
});
...
subscription.off();