public
Last active

using an event aggregator with backbone

  • Download Gist
1-referencing.js
JavaScript
1 2 3 4 5 6 7 8 9 10
MedicationView = Backbone.View.extend({
events: {
"click #edit": "editMedication"
},
 
editMedication: function(){
var editView = new AddEditView({model: this.model});
editView.render();
}
});
2-reference-instance.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
MedicationView = Backbone.View.extend({
events: {
"click #edit": "editMedication"
},
 
initialize: function(options){
this.addEditView = options.addEditView;
}
 
editMedication: function(){
this.addEditView.render();
}
});
 
// initialize everything here...
// 'medicationList' is a collection of medications
var addEditView = new AddEditView(...);
 
medicationlist.each(function(med){
new MedicationView({model: med, addEditView: addEditView});
}
3-routing.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
MedicationRouter = Backbone.Router.extend({
routes: {
"edit/:id": "editMedication"
},
 
editMedication: function(id){
var med = medicationList.get(id);
this.addEditView.editMedication(med);
}
});
 
AddEditView = Backbone.View.extend({
 
editMedication: function(medication){
this.model = medication;
this.render();
}
 
});
4-vent.js
JavaScript
1
var vent = _.extend({}, Backbone.Events);
5-event-aggregation.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 34 35 36
AddEditView = Backbone.View.extend({
initialize: function(options){
_.bindAll(this, "editMedication");
options.vent.bind("editMedication", this.editMedication);
},
 
editMedication: function(medication){
this.model = medication;
this.render();
}
});
 
MedicationView = Backbone.View.extend({
events: {
"click #edit": "editMedication"
},
 
initialize: function(options){
this.vent = options.vent;
},
 
editMedication: function(){
this.vent.trigger("editMedication", this.model);
}
});
 
// initialize everything, and tie it all together
// with the event aggregator object: vent
 
var vent = _.extend({}, Backbone.Events);
 
var addEditView = new AddEditView({vent: vent});
 
medicationList.each(function(med){
new MedicationView({model: med, vent: vent});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.