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 see the events module reference documentation for more detailed information on these.
Some exmaples of using the app module's events are demonstrated below.
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's 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
});
Un-subscribing from an app-wide message.
var subscription = app.on('customer:new').then(function(customer){
//do something with the payload
});
...
subscription.off();