I am learning jQuery/JavaScript best practices and am attempting to put them into practice. My overall goal is to have lots of small, independent .js files which contain specific functionality and will not intrude or collide with other files, then concat/minify them for production as one file; basing some concepts off of John Papa's AngularJS Style Guide.

I'm trying to understand IIFEs and jQuery delegate event handling. I am not sure if this is the best way to do this, but my attempt here is to isolate a specific event handler in its own contained block. If an IIFE is used, does this event remain registered/delegated to the span or does the IFFE invoke once and the event is no longer registered?

I'm not worried about the code working but more concerned with learning how to structure jQuery Event Delegates in a modular way using the example below.

(function(window, document, $){
   var $icon = $('.icon');

   $icon.on('click', 'span', function() {
      var me = this;

})(window, document, jQuery);
  • \$\begingroup\$ Yes, the event stays registered. \$\endgroup\$ – Gary Storey Mar 23 '16 at 16:06
  • \$\begingroup\$ @Gary Storey Great, thank you! And is this a common practice, i.e. putting blocks of code into separate self-contained files in their own anonymous IIFE's? \$\endgroup\$ – user100935 Mar 23 '16 at 20:23
  • \$\begingroup\$ I do it all the time. Then I use a build tool, gulp in my case, to lint and the concatenate the files. \$\endgroup\$ – Gary Storey Mar 24 '16 at 16:29
  • \$\begingroup\$ Also, you should make sure to add 'use strict'; immediately inside the IIFE to put your code into JS strict mode. \$\endgroup\$ – Gary Storey Mar 24 '16 at 16:30
  • \$\begingroup\$ @GaryStorey yep added 'use strict'; to the IIFE. I was also going to look at concatenation and minification of my JS files too. I'll look at some tools and see what works for me. Thanks! \$\endgroup\$ – user100935 Mar 26 '16 at 2:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy