I have recently been getting into the habit of leveraging the revealing module pattern for all my code. I used this guide for inspiration, but my code doesn't feel as elegant.
var styleGuide = (function styleGuideHandler() {
'use strict';
var publicAPI,
intervalId = null,
clipboard = new Clipboard('.copyButton'),
btns = document.querySelectorAll('.style-guide');
function setTooltip(btn, message) {
$(btn).attr('data-original-title', message);
setTimeout(function() {
$(btn).tooltip('show');
}, 150);
}
function hideTooltip(btn) {
if (intervalId !== null) {
clearTimeout(intervalId);
}
intervalId = setTimeout(function() {
$(btn).tooltip('hide');
intervalId = null;
}, 500);
}
publicAPI = {
init: function() {
clipboard.on('success', function(e) {
setTooltip(e.trigger, 'Copied!');
hideTooltip(e.trigger);
e.clearSelection();
console.log(e);
});
clipboard.on('error', function(e) {
setTooltip(e.trigger, 'Failed!');
hideTooltip(e.trigger);
console.log(e);
});
$('.copyButton').tooltip({
trigger: 'click',
placement: 'bottom'
});
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
/* preventDefault on buttons */
for (var i = 0, l = btns.length; i < l; i++) {
btns[i].addEventListener('click', function(e) {
e.preventDefault();
e.stopPropagation();
});
}
}
};
return publicAPI;
})();
$(document).ready(styleGuide.init);
Also, would executing the ready
function like this $(document).ready(function(){styleGuide.init});
encapsulate the module further? Meaning, there would be no chance the styleGuide
module could overwritten?
-
\$\begingroup\$ I have rolled back Rev 5 → 4. Please see What to do when someone answers . \$\endgroup\$200_success– 200_success2016年12月08日 19:07:46 +00:00Commented Dec 8, 2016 at 19:07
1 Answer 1
Interesting question, your code is very readable.
However, if you only reveal an init
function, then really there is not much sense in using a revealing pattern.
I would probably not self execute styleGuideHandler
but pass it to the jQuery call:
$(document).ready(styleGuideHandler);
Other than that, just for giggles, I might also pass the few globals it uses:
$(document).ready(styleGuideHandler( document, Clipboard, hljs ));
Then when styleGuideHandler
is executed, you run the code in init
.
-
\$\begingroup\$ Thank you so much Konijn! I tried to refactor the original code based on what you prescribed. On last thing—let's say someone in the future added a script tag with a function object with the same name before this
$(document).ready((function(){styleGuide.init}());
, Would wrapping the function object in a IIFE like I did here when passing it to thedocument.ready
act as a protective wrapper of sorts? \$\endgroup\$Antonio Pavicevac-Ortiz– Antonio Pavicevac-Ortiz2016年12月08日 18:32:59 +00:00Commented Dec 8, 2016 at 18:32 -
\$\begingroup\$ @AntonioOrtiz Not really, I see no added value \$\endgroup\$konijn– konijn2016年12月09日 16:14:20 +00:00Commented Dec 9, 2016 at 16:14
Explore related questions
See similar questions with these tags.