Skip to content

Instantly share code, notes, and snippets.

@blackjk3
Created December 23, 2011 16:12
Show Gist options
  • Save blackjk3/1514593 to your computer and use it in GitHub Desktop.
Save blackjk3/1514593 to your computer and use it in GitHub Desktop.
Backbone modules?
/**
* @author: itooamaneatguy
*
* Question:
* What is the best way to construct reusable modules using Backbone.js??
*
*/
/**
* Example 1: One module for app views. One module for models.
* Advantages: Clear where views are located and where models are located.
* Disadvantages: Since each view and module are coupled to the module they are not very reusable.
*/
var NAMESPACE = NAMESPACE || {};
NAMESPACE.AppViews = (function() {
var PhotoView, GalleryView, AboutView;
PhotoView = Backbone.View.Extend({});
GalleryView = Backbone.View.Extend({});
AboutView = Backbone.View.Extend({});
return {
PhotoView: PhotoView,
GalleryView: GalleryView,
AboutView: AboutView
};
})();
NAMESPACE.AppModels = (function() {
var PhotoModel, GalleryModel, AboutModel;
PhotoModel = Backbone.View.Extend({});
GalleryModel = Backbone.View.Extend({});
AboutModel = Backbone.View.Extend({});
return {
PhotoModel: PhotoModel,
GalleryModel: GalleryModel,
AboutModel: AboutModel
};
})();
/**
* Example 2: Separate components for each view/model combination.
* Advantages: Modules are more reusable since all logic is wrapped per component.
* Disadvantages: Views and models are coupled together.
*/
var NAMESPACE = NAMESPACE || {};
NAMESPACE.PhotoModule = (function() {
var PhotoView, PhotoModel;
PhotoView = Backbone.View.Extend({});
PhotoModel = Backbone.View.Extend({});
return {
PhotoView: PhotoView,
PhotoModel: PhotoModel
};
})();
/**
* Example 3: Wrap module functionallity entirly within a constructor function
* Advantages: Most resuable. Module is easily invoked with new NAMESPACE.PhotoModule
* Disadvantags: Assumes module will use view and model together.
*/
var NAMESPACE = NAMESPACE || {};
NAMESPACE.PhotoModule = (function() {
var Photo, PhotoView, PhotoModel;
PhotoView = Backbone.View.Extend({});
PhotoModel = Backbone.View.Extend({});
Photo = function() {
this.model = new PhotoModel();
this.view = new PhotoView({model:this.model});
};
return Photo;
})();
// Ex. Invoke NAMESPACE.PhotoModule
var photoModule = new NAMESPACE.PhotoModule();
console.log(photoModule.view);
console.log(photoModule.model);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment