Skip to content

Instantly share code, notes, and snippets.

@mbunge
Last active August 29, 2015 14:16
Show Gist options
  • Save mbunge/906329b5988930b9782a to your computer and use it in GitHub Desktop.
Save mbunge/906329b5988930b9782a to your computer and use it in GitHub Desktop.
Inversion of control for dom element. Get in touch and follow at twitter http://twitter.com/makk_eightbit! Thank you!
/**
* @author Marco Bunge <marco_bunge@web.de>
* @copyright 2015 Marco Bunge http://marco-bunge.de
* @licence MIT http://opensource.org/licenses/MIT
*
* Get in touch and follow me at twitter http://twitter.com/makk_eightbit! Thank you!
*
* Inversion of control for dom elements.
* Allows you to bind custom logic, plugins, etc. to a dom element.
* The binding is referencing passed data attributes.
* If data-option-* has been set, options will available in callback.
*
* data-instance: instance name referencing instance name
* data-option-*: custom options for instance
* HTML:
* <div data-instance="myInctance" data-attr-foo="bar"></div>
*
* JS:
* <script type="text/javascript">
* jq.domIoC('myInstance', function (element, options) {
* element.text(options.foo);
* element.bazPlugin(options);
* bazPlugin(element,options);
* });
* </script>
*/
(function (jq, undefined) {
var lcFirst = function (s) {
var f;
s += '';
f = s.charAt(0).toLowerCase();
return f + s.substr(1);
};
var parseOptions = function (data) {
var options = {},
optionKeyword = 'attr',
optionName;
for (var optionKey in data) {
if (!data.hasOwnProperty(optionKey)) {
continue;
}
if (optionKey.substr(0, optionKeyword.length) != optionKeyword) {
continue;
}
optionName = lcFirst(optionKey.substr(optionKeyword.length));
options[optionName] = data[optionKey];
}
return options;
};
jq.domIoC = function (instanceName, callback) {
var element,
options;
element = jq('[data-instance="' + instanceName + '"]');
options = parseOptions(element.data());
if (jq.isFunction(callback)) {
callback(element, options)
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment