Skip to content

Instantly share code, notes, and snippets.

@girlcheese
Created October 4, 2015 13:46
Show Gist options
  • Save girlcheese/aa5f77c0b87cb872b8fc to your computer and use it in GitHub Desktop.
Save girlcheese/aa5f77c0b87cb872b8fc to your computer and use it in GitHub Desktop.
// -------------------------------------------------------------------------------------------------
// init widgets
/**
* DOM-based routing module for page initialisation.
* @module initWidgets
* @author samc@fullsixuk.com
*
*/
function initWidgets(scope, trycatch) {
var $nodes = $('[data-widget]', scope),
n = $nodes.length,
widgetClasses,
j;
if (!n) {
return false;
}
function exec() {
// Iterate over DOM nodes, extract widget names and options and apply on-demand
for (n; n--;) {
// This is init code - any exception here will break the page
widgetClasses = $nodes[n].getAttribute('data-widget').replace(/^\s*|\s*$/g, '').split(/\s+/);
for (j = widgetClasses.length; j--;) {
var widgetClass = $.camelCase(widgetClasses[j]);
if (widgetClass && widgetClass in $.fn) {
var widgetOptions = $($nodes[n]).data(widgetClass.toLowerCase() + 'Options');
widgetOptions = (typeof widgetOptions === 'object') ? widgetOptions : {};
$($nodes[n])[widgetClass](widgetOptions);
}
else {
console.error('init widgets: class not found: <node widget=\'', widgetClass, '\'> = ', $nodes[n]);
}
}
}
}
if (trycatch) {
try {
exec();
}
catch (e) {
console.error('initWidgets(): exception - ' + e);
}
}
else {
exec();
}
}
$.fn.initWidgets = function (trycatch) {
initWidgets(this, trycatch);
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment