Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone events with wildcards

Is there a way to listen to all events of a namespace. So when I listen to an event like this:

app.vent.on('notification(:id)', function(type){console.lof(type)})

It will listen to all events likes this:

app.vent.trigger('notification:info')
app.vent.trigger('notification:error')
app.vent.trigger('notification:success')
like image 782
Andreas Köberle Avatar asked Mar 08 '13 14:03

Andreas Köberle


2 Answers

No. Backbone typically fires a general eventName event, as well as eventName:specifier event. An example of this is Model.change, which allows you to listen to all changes, as well as changes to individual fields:

model.on('change', this.onAnyPropertyChanged);
model.on('change:name', this.onNamePropertyChanged);

Following this pattern in your code, you could trigger your events as follows:

app.vent.trigger('notification', 'info');
app.vent.trigger('notification:info');

And listen to the general event:

app.vent.on('notification', function(type){ 
  console.log(type);  //-> "info"
}); 
like image 190
jevakallio Avatar answered Oct 02 '22 00:10

jevakallio


As mentioned by in this answer it is not possible to listen events with wildcards. But as you can listen to all this will work:

vent.on('all', function(evenName, options) {
  var type = evenName.split(/notification:/)[1];
  if (type) {
    console.log(type, options);
  }
});
like image 34
Andreas Köberle Avatar answered Oct 02 '22 01:10

Andreas Köberle