Search code examples
javascripteventsbackbone.jsmediatorcustom-events

Backbone: events from external mediator source


I'm starting implementing Backbone in a web app.

The app has already some objects of its own, and also a Mediator (here called EventTools) for cross-object event communication. So for ex. an object subscribes like this:

  EventTools.add({

    "gt_pos_ready":function(coords){
      //code;
    }.bind(this),

  });

And then some other object fires the event:

EventTools.fire("gt_pos_ready", args..);

Fine. But what if I want a view or other Backbone object to listen to EventTools firing some event?


Solution

  • You can use Backbone.Events instead of your own way to trigger and listen events:

    _.extend(EventTools, Backbone.Events);
    
    EventTools.on("gt_pos_ready", function(coords) {
      /*Code for gt_pos_ready()*/
    });
    
    EventTools.trigger("gt_pos_ready", {LNG:"40.542343",LAT:"32.232423"});
    

    I'm sure you are using lodash/underscore because it's a Backbone dep, so this should work.