Magic events with wildcards

Is there a way to listen for all namespace events. Therefore, when I listen to such an event:

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

He will listen to all events that like this:

 app.vent.trigger('notification:info') app.vent.trigger('notification:error') app.vent.trigger('notification:success') 
+7
source share
4 answers

Not. The trunk typically fires the general eventName event, as well as the 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 can 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" }); 
+9
source

As mentioned in this answer , it is not possible to listen to events using wildcards. But since 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); } }); 
+5
source

I wrote this helper:

 export default class EventsHelper { static triggerNamespacedEvent(eventBus, event, args) { event.split(':').reduce((previous, current) => { eventBus.trigger(previous, current); return `${previous}:${current}`; }); eventBus.trigger(event, args); } } 

To use this in your view, you must:

 actionOne(argsOne){ EventsHelper.triggerNamespacedEvent(this, 'click:chart:one', argsOne); } actionTwo(argsTwo){ EventsHelper.triggerNamespacedEvent(this, 'click:chart:two', argsTwo); } 

To listen to these events, you will do:

 //Listen for all clicks this.listenTo(view, 'click', (args) => { console.log(`clicked something: ${args}`); //output: clicked something: chart }); //Listen for all chart clicks this.listenTo(view, 'click:chart', (args) => { console.log(`clicked chart: ${args}`); //output: clicked chart: one }); //Listen for fully qualified event this.listenTo(view, 'click:chart:two', (args) => { console.log(`clicked chart two: ${args}`); //output: clicked chart two: evtArgs }); 
+2
source

A warning. Listening for event namespaces in custom events may no longer work. For example, this does not work:

  @listenTo @app, 'session', -> console.log ".listenTo `session` triggered" @listenTo @app, 'session:login_success', -> console.log ".listenTo `session:login_success` triggered" @app.on 'session', -> console.log ".on `session` triggered" @app.on 'session:login_success', -> console.log ".on `session:login_success` triggered" 

If I run 'session: login_success' in @app , only two specific events fire, not the namespace.

Github related issue: https://github.com/documentcloud/backbone/issues/2558

+1
source

All Articles