Skip to content

Instantly share code, notes, and snippets.

@lokothodida
Created July 13, 2015 14:57
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 lokothodida/f0cd4179c968bc09351f to your computer and use it in GitHub Desktop.
Save lokothodida/f0cd4179c968bc09351f to your computer and use it in GitHub Desktop.
jQuery Nested Plugins Bonuses
;(function($, window, document, undefined) {
// == BONUS 1 ==
// Others can add to your modules by extending $.fn.plugin.modules literal
// E.g: (accessed with $(selector).plugin().externalModule(opts))
$.fn.plugin.modules.externalModule = function(opts) {
// Code for this plugin ...
};
// == BONUS 2 ==
// You can nest your modules as far as you want them to
// E.g:
$.fn.plugin.modules.module4 = function(opts) {
if (!arguments.length) {
return $.fn.plugin.getModules(this, $.fn.plugin.modules.module4.modules);
}
// Code for this plugin ...
};
// Initialize the @modules object for @module4 ...
$.fn.plugin.modules.module4.modules = {};
// Now add a sub module
// Accessible with $(selector).plugin().module4().submodule()
$.fn.plugin.modules.module4.modules.submodule = function(opts) {
// Code for this plugin ...
};
// == BONUS 3 ==
// Assuming that you don't form any cyclic dependencies between your modules
// you can utilize one module from within another
// E.g:
$.fn.plugin.modules.module5 = function(opts) {
// ...
var init = function(i, elem) {
var $elem = $(elem);
// Access Module 4
$elem.find('#something').plugin().module4(otherOpts1);
// If there were modules in module 5, we could do:
$elem.find('#somethingelse').plugin().module5().someOtherModule(otherOpts2);
};
return this.each(init);
};
// == BONUS 4 ==
// You can wrap event handlers/triggers like .click(...) does for .on('click', ...)
// E.g:
// $(selector).plugin().someEvent() triggers 'someEvent' on the elements
// $(selector).plugin().someEvent(callback) binds the @callback to the event
// $(selector).plugin().someEvent(data, callback) binds the @callback to the
// event and passes @data to it
$.fn.plugin.modules.someEvent = function(param1, param2) {
return this.each(function(i, elem) {
var $elem = $(elem);
if ($.isFunction(param1)) {
$elem.on('someEvent', param1);
} else if ($.isPlainObject(param1) && $.isFunction(param2)) {
$elem.on('someEvent', null, param1, param2);
} else {
$elem.trigger('someEvent');
}
});
};
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment