My app
module bootstraps a Backbone.js application.
I need app
to be available in every other view for easy access to router, triggering navigation, etc.
I never ported an app to RequireJS before, and I got stuck on circular dependency problem, and this answer isn't quite clear to me, so I'm not sure if I applied the solution correctly.
I'm using AMD sugar style throughout the app, so here's what I came up with:
app.js
define(function (require, exports) {
'use strict';
var _ = require('underscore'),
Backbone = require('backbone'),
Router = require('Router'),
AppView = require('common/views/app_view'),
// ...
return _.extend(exports, {
start: function () {
this.router = new Router();
Backbone.history.start();
this.appView = new AppView();
this.appView.render();
},
// ...
});
});
Extending exports
instead of directly returning an object allows me to do app = require('app')
in any view of the app without worrying about circular dependencies.
All other modules in the app return value normally (i.e. I'm not using exports
anywhere else).
Is this an OK strategy for a Require.js Backbone app?
Are there better solutions (that will also work with optimizer or Almond)?
An example of how I'm using app
in a (rather deeply nested) view:
zine_item_view.js
define(function (require) {
'use strict';
var View = require('common/views/view'),
Misc = require('common/helpers/misc'),
app = require('app');
var ZineItemView = View.extend({
template: 'templates/social/items/zine_item.html',
events: {
'click': 'showZine'
},
showZine: function (e) {
if (!Misc.shouldHandleClick(e)) {
return;
}
app.presenter.showZine({
zine: this.model,
route: app.router.routeToZineTrending(this.model.id)
});
}
});
return ZineItemView;
});
app
? \$\endgroup\$app.presenter.showZine
supposed to do here ? Are you setting a route inside of aView
? \$\endgroup\$presenter
is not a view, it's a separate object that has methods likeshowZine
,showUser
,showHome
, etc. Think of it as of a simple “controller” (although there are no controllers in Backbone per se). It manages the root view. It often needs to load a model asynchronously, and, when it is ready, updates both root view and the current route. \$\endgroup\$