Created
September 11, 2014 21:32
-
-
Save sciolist/30c4856c1ba86813906d to your computer and use it in GitHub Desktop.
jQuery.feature
This file contains 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
(function ($, window, undefined) { | |
"use strict"; | |
$.feature('js-alert', function (el, value) { | |
$(el).click(function () { alert(value); }); | |
}); | |
})(jQuery, window); |
This file contains 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
<!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> |
This file contains 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
(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