Implementing a click
listener globally may seem like a quick solution, but as your application scales, it can become cumbersome to manage. A better approach is to treat each View
as its own entity, only concerned with events within itself. When interaction between views is necessary, a coordination mechanism is needed.
An effective method is to utilize a Model as an event bus for communication between views:
var ViewWithSearch = Backbone.View.extend({
events: {
'click .search' : 'searchKey'
},
initialize: function(options) {
this.eventModel = options.eventModel;
},
searchKey: function(event) {
this.eventModel.trigger('search', event)
}
});
var ReactingView = Backbone.View.extend({
initialize: function(options) {
this.listenTo(options.eventModel, 'search', this.onSearch);
},
onSearch: function(eventModel, event) {
console.log("Search was clicked!");
}
});
var eventModel = new Backbone.Model();
new ViewWithSearch({
eventModel: eventModel
}).render();
new ReactingView({
eventModel: eventModel
}).render();
While more intricate than the global event approach, this method aligns with the MV*
design pattern. It results in views that are loosely coupled and self-contained, facilitating easier maintenance and testing.
Various libraries are available to facilitate this type of functionality; one example is Backbone.Radio, designed specifically for this purpose.