I'm building a web application with various visualization components, made up of Backbone.js Models and Views:
The "PopulationVisualization component" might for example have:
All of these components depend on external dataManagers and dataSource objects but otherwise they are supposed to be decoupled.
On a given page, I'd like to instantiate an instance of the PopulationVisualization component. I'd also like to listen for changes in the main model of that component so that I could serialize its state in the URL.
1) What would this look like if I tried adopting the AMD module pattern?
2) Would I make one module of the PopulationVisualization component or several?
3) Would I expose module-level methods as an API or would I provide direct manipulation of the inner Models and Views?
Thanks.
To answer you questions, here's my advice, answering all three:
Modules should be as small as possible, so I would create a new module for each view, one for the module, and one for the serialization logic. Then I would create one module that ties all this together so that outside code doesn't have to deal with models, views, or serialization.
Here is my first stab at something like this:
// components/populationVisualization/Model.js
define(function (require, exports, module) {
return Backbone.Model.extend({ /* ... */});
});
// components/populationVisualization/views/Timeslider.js
define(function (require, exports, module) {
return Backbone.View.extend({ /* ... */});
});
// components/populationVisualization/views/Legend.js
define(function (require, exports, module) {
return Backbone.View.extend({ /* ... */});
});
// components/populationVisualization/serializer.js
define(function (require, exports, module) {
exports.setupSerialization = function (model) {
// ...
};
});
// components/populationVisualization.js
define(function (require, exports, module) {
var Model = require("./populationVisualization/Model");
var TimesliderView = require("./populationVisualization/views/Timeslider");
var LegendView = require("./populationVisualization/views/Legend");
var serializer = require("./populationVisualization/serializer");
exports.createAndRender = function (modelParams, $el) {
var model = new Model(modelParams);
serializer.setupSerialization(model);
var timesliderView = new TimesliderView({ model: model });
var legendView = new LegendView({ model: model });
$el.append(timesliderView.el);
$el.append(legendView.el);
};
});
Elsewhere in the app you would only require("components/populationVisualization")
and call that module's createAndRender
method with the appropriate parameters.