Leveraging Publish and Subscribe

####

Key Points

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:

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.

Note: 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();