I found this code in the <head> section of an HTML page (a collegue made this but he doesn’t work here anymore):
(function(window, PhotoSwipe){
document.addEventListener('DOMContentLoaded', function(){
var options = {},
instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
}, false);
}(window, window.Code.PhotoSwipe));
While I can understand the central part (from document.addEventListener), I can’t understand the first and the last line. What they’re doing here? The code is from an open source image gallery called PhotoSwipe. Any pointer is appreciated.
[EDIT]
Is this code the same as:
document.addEventListener('DOMContentLoaded', function(){
var options = {},
instance = window.Code.PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
}, false);
?
This is a self-executing protected bit of code. Let’s break it down:
The parenthesis cause our code to be executed on its own, without anything else invoking it.
This creates references to
windowandwindow.Code.PhotoSwipethat cannot be tampered with by outside code. So within our parens,PhotoSwipeis a protected alias ofwindow.Code.PhotoSwipe. Andwindow, though the name doesn’t differ, is also a protected reference to the external globalwindowobject.The next line, the
addEventListenerline, could be rewritten to bring its anonymous function out as a named function:Note, this is functionally the same thing you have in your original code, only we’ve pulled the function out of the
addEventListenercall and gave it a name.addEventListenerattaches a callback function to handler certain events. In this case, we’re handling the eventDOMContentLoaded. This event is being listened for on thedocumentobject. Anytime this event is heard, we respond by callingmyFunc.The last parameter,
false, deals with capturing and bubbling. These are two methods events propagate throughout the DOM. When Capturing, events move from the top of the DOM inward. When Bubbling, they move from the inside of the DOM outward. Usingfalsestates you want to handle this in itsbubblingphrase.Within
myFunct, which is called anytime theDOMContentLoadedevent happens on thedocument, we have one line of code which first declares a new object calledoptions. This object is empty, having no members.Secondly, you are passing in two arguments to the
attachmethod of thePhotoSwipeobject. The first method is a selector. What is does it searches the DOM for elements that match#Gallery a, meaning any anchor element inside an element having the ID “Gallery”. That would mean all of the following:Or
This is associated with the empty object that we created. What
PhotoSwipedoes internally is unknown at this point, since that code is not presented here.