Skip to content

Instantly share code, notes, and snippets.

@sciolist
Created September 11, 2014 21:32
Show Gist options
  • Save sciolist/30c4856c1ba86813906d to your computer and use it in GitHub Desktop.
Save sciolist/30c4856c1ba86813906d to your computer and use it in GitHub Desktop.
jQuery.feature
(function ($, window, undefined) {
"use strict";
$.feature('js-alert', function (el, value) {
$(el).click(function () { alert(value); });
});
})(jQuery, window);
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery.feature.js"></script>
<script src="alert.js"></script>
</head>
<body>
<button js-alert="You have clicked the button">Click me</button>
</body>
</html>
(function (jQuery, window, undefined) {
"use strict";
jQuery.feature = createFeature;
jQuery.fn.feature = triggerFeature;
jQuery(function() { jQuery(document).feature(); });
function createFeature(name, callback) {
jQuery(document).on('feature', function (evt, root) {
var selector = '[' + name + ']:not([' + name + '--loaded])';
var items = jQuery(root).find(selector).addBack(selector);
items.each(function () {
var self = $(this);
if (self.parentsUntil(root, '[js-feature-block]').length) return;
self.attr(name + '--loaded', '');
try {
callback(self[0], self.attr(name));
} catch(ex) {
console && console.error(ex);
}
});
});
}
function triggerFeature() {
jQuery(document).trigger('feature', this);
return this;
};
})(jQuery, window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment