Skip to content

Instantly share code, notes, and snippets.

@reedlauber
Created July 3, 2012 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reedlauber/3040693 to your computer and use it in GitHub Desktop.
Save reedlauber/3040693 to your computer and use it in GitHub Desktop.
Component Patterns
/* ------- */
/* MANAGER */
/* ------- */
MyApp.Manager = function(options) {
var _self = {},
_options = $.extend({
components: {}
}, options);
_self.init = function() {
$.each(_options.components, function(id, comp) {
comp.init(_self);
});
return _self;
};
return _self;
};
/* --------- */
/* VERSION 1 */
/* --------- */
// Component Definition
MyApp.Users = function(options) {
var _self = {},
_options = $.extend({
id: 'users',
target: '#content'
}, options),
_manager;
// Other construction-time assignments and private variables/functions
_self.init = function(manager) {
_manager = manager;
// Initialization-time code (i.e. read DOM, setup events, AJAX, etc)
return _self;
};
return _self;
};
// Usage in all three cases
MyApp.Manager({
components: {
users: MyApp.Users({ id:'admin-users' })
}
}).init();
/* --------- */
/* VERSION 2 */
/* --------- */
// Component Factory
MyApp.component = function(defaults, options) {
options = options || defaults;
var _c = {
options: $.extend({ target:'#content' }, defaults, options),
pub: {}
};
_c.pub.init = function(manager) {
_c.manager = manager;
if(_c.oninit) {
_c.oninit.call(_c);
}
return _c.pub;
};
return _c;
};
// Component Definition
MyApp.Users = function(options) {
var _c = MyApp.component({ id:'users' }, options);
// Other construction-time assignments and private variables/functions
_c.oninit = function() {
// Initialization-time code (i.e. read DOM, setup events, AJAX, etc)
// _c provides access to options, manager, and public object
// No need to return "_self" for chaining
};
return _c.pub;
};
/* --------- */
/* VERSION 3 */
/* --------- */
// Component Factory
MyApp.component = function(defaults, oninit) {
if(typeof defaults === 'function') {
oninit = defaults;
defaults = {};
}
var _c = { options: $.extend(MyApp.component.defaults, defaults) },
_p = {};
return function(options) {
_c.options = $.extend(_c.options, options);
_p.init = function(manager) {
_c.manager = manager;
var $el;
if(_c.options.id) {
$el = _c['$' + _c.options.id] = $('#' + _c.options.id);
}
if(typeof oninit === 'function') {
oninit.call(_c, _c.options, _p, $el);
}
return _p;
};
return _p;
};
};
MyApp.component.defaults = { target:'#content' };
// Component Definition
MyApp.Users = MyApp.component({
id: 'users'
}, function(opts, pub, $el) {
var comp = this;
// Initialization-time code (i.e. read DOM, setup events, AJAX, etc)
// Access to options, public, manager through arguments
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment