public
Created — forked from derickbailey/1.js

revisiting event aggregator

  • Download Gist
1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
MyApp = {};
MyApp.vent = _.extend({}, Backbone.Events);
 
MyApp.vent.on("some:event", function(){
//do stuff common to ALL events
//usually you won't have logic here
});
 
 
var ObservingModel = Backbone.Model.extend({
initialize : function () {
MyApp.vent.bind('some:event', this.reactToObservation)
},
reactToObservation : function() { console.log('event came through loud and clear'); }
});
 
MyApp.vent.trigger("some:event");
2.js
JavaScript
1 2 3 4 5 6 7
MyApp = new Backbone.Marionette.Application();
 
MyApp.vent.on("some:event", function(){
alert("some event was fired!");
});
 
MyApp.vent.trigger("some:event");
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
MyApp = new Backbone.Marionette.Application();
 
MyApp.UserManagement = (function(Backbone){
var mgmt = {};
var mgmtEvents = new Backbone.Marionette.EventAggregator();
 
mgmt.UserListView = Backbone.View.extend({
events: {
"click .user": "userClicked"
},
 
userClicked: function(){
var user = // get the user that was clicked
mgmtEvents.trigger("user:selected", user);
},
 
// ...
});
 
mgmt.UserDetailView = Backbone.View.extend({
// ...
});
 
mgmtEvents.on("user:selected", function(user){
var view = new mgmt.UserDetailView({
model: user
});
view.render();
$("#detail").html(view.el);
});
 
return mgmt;
})(Backbone);
4.js
JavaScript
1 2 3 4 5
MyApp.vent.on("myChannel", "myEvent", function(){
// do stuff here
});
 
MyApp.vent.trigger("myChannel", "myEvent");
5.js
JavaScript
1 2 3 4 5 6 7 8 9 10
MyApp.myChannel = _.extend({}, Backbone.Events);
MyApp.anotherChannel = _.extend({}, Backbone.Events);
 
MyApp.myChannel.on("someEvent", function(){
// ...
});
 
MyApp.myChannel.on("anotherEvent", function(){
// ...
});
6.js
JavaScript
1 2 3 4 5
MyApp.vent.on("some:namespaced:event", function(){
// ...
});
 
MyApp.vent.trigger("some:namespaced:event");

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.