I am working on a small backbone application.
I currently got the problem that I want to show a profile of a specific item.
This showProfile event is triggered when I click on list item. Not the showProfile event needs to inform the parent listView which informs the above sidebarView which informs the mainView which now can instance the profileView.
This would involve three to four views in the event chain. Is there a possible workaround for this problem?
Regards, Bodo
I don't know if it's the best way, but for this kind of scenario, I've used an application-level event aggregator by creating an object which has an event property that extends Backbone.Events.
I tend to use the same object for storing application-wide settings as well:
var app = {
settings: {},
events: _.extend({}, Backbone.Events),
};
You can then trigger a showProfile event from your view and bind to app.event in your mainView, without bubbling through all the parent views.
When using RequireJS, I create an app module, which is a dependency for my views:
define([
"jquery",
"underscore",
"backbone"
],
function($, _, Backbone) {
var app = {
root: "/",
settings: {},
events: _.extend({}, Backbone.Events),
};
return app;
});
I also tend to place my router on the app object in case I need to access it in a view, so in my main.js (like in backbone-boilerplate):
require([
"app",
"router",
],
function(app, Router) {
app.router = new Router();
Backbone.history.start({ pushState: true, root: app.root });
});
You might want to read Derick Bailey's blog posts about event aggregators: