2

I've picked up a project and all the js files are written as modules like below and then concatenated into one minified file.

Is there any benefits to writing the js files like this? For example on the project its not using multiple 'Footer' objects so surely theres no need to abstract it and should just do self invoking functions?

function Footer(){
   var $elements = {
       slideButton  : $('.js-footer-slide-btn'),
       slideBlock   : $('.js-footer-slide-block')
   };

   this.initialise = function(){
       $elements.slideButton.click(function(){
           $(this).toggleClass('active').next().stop().slideToggle();
       });
   };
}

var footer = new Footer();
    footer.initialise();
Adam
  • 812
  • 3
  • 13
  • 22
  • Well, if that's the only invocation of `Footer` then it does hardly make sense indeed. Just use an IIFE. Also, `initialise` is only called once as well, right? – Bergi Aug 14 '15 at 09:59
  • Cheers I'll take a look into IIFE. Yep for each object atleast – Adam Aug 14 '15 at 10:12
  • @ Adam: [IIFE](http://stackoverflow.com/q/8228281/1048572) are just the "self-invoking functions" you were talking of. – Bergi Aug 14 '15 at 10:14

2 Answers2

1

One advantage you may have overlooked is that you do not pollute the global space. So you can write many initialise() methods for every object without having naming conflicts between your "modules", or with other external JS libraries.

Cranio
  • 9,647
  • 4
  • 35
  • 55
0

There are no classes in Javascript but it has a constructor functions and here you are creating a new object using its constructor. So when a constructor function is invoked using new 1) An empty object is created inheriting the prototype of the function 2) properties & method will be added which will be referenced by this.

If this snippet is only use to handle the event there is no point of doing this using constructor function.

It can be done using event delegation. $('body').on('eventType Exp:click,keypress etc','targetElement',callbackFunction);

Beside footer.initialize(pass the parameter here) rather that creating an $elements object literal inside the function

brk
  • 48,835
  • 10
  • 56
  • 78