Created
October 4, 2015 13:46
-
-
Save girlcheese/aa5f77c0b87cb872b8fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ------------------------------------------------------------------------------------------------- | |
// init widgets | |
/** | |
* DOM-based routing module for page initialisation. | |
* @module initWidgets | |
* @author [email protected] | |
* | |
*/ | |
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