I am trying to better structure my events in backbone. Currently I have one view communicating with another by triggering events within a function, and listening for events in another function, like:
//childView
triggerFilterChange: function(e){
Backbone.trigger('filterChange',activeFilters);
}
//parentView
initialize: function(){
Backbone.on('filterChange', this.onFilterChange, this);
},
onFilterChange:function(filters){
//DO STUFF
}
This works, however, I would like to make it more clear in my child view what events should be expected, rather than just triggering something from a random function somewhere buried within the view. For example, all of my click events for the child view are clearly delineated at the top of the page:
define([
'jquery',
'underscore',
'backbone',
], function($, _, Backbone){
var ProductsFiltersView = Backbone.View.extend({
events : {
"click .filter-options-container" : "filterOptionContainerClick",
"click .filter-option" : "filterOptionClick",
},
So my question is, is there a way to put custom events into this events object? Or some structure similar to this, so you know at the top of the view what events might be triggered? Like:
events : {
"click .filter-options-container" : "filterOptionContainerClick",
"click .filter-option" : "filterOptionClick",
"filterChange" : "doFilterChange"
},
doFilterChange: function(){
Backbone.trigger('parentFilterChange',activeFilters);
}
I wouldn't touch the events object for this anyhow.
The event object defines the events from child elements of el that are propagated to the parent element (el).
The question is more about how you glue different views together.
I use intermediary custom objects (which I call controllers, as Backbone does not provide Controllers out of the box) that are used to instantiate the views and listen to events that were triggered from within the view.
You can use specified event aggregators to use within particular 'controller' objects to handle the events.
MyApp = {};
MyApp.some_vent = _.extend({}, Backbone.Events);
MyApp.some_vent.on("some:event", function(){
alert("some event was fired!");
});
If the controller holds a reference to the view where you want to cause some effect, you can execute these view's methods accordingly.