Understanding Unclear JavaScript Code

I found this code in a section <head>on an HTML page (colleagues did this, but it no longer works here):

(function(window, PhotoSwipe){ 
    document.addEventListener('DOMContentLoaded', function(){
        var options = {},
            instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
    }, false);
}(window, window.Code.PhotoSwipe));

As long as I understand the central part (from document.addEventListener), I cannot understand the first and last line. What are they doing here? The code from the open source image gallery is called PhotoSwipe. Any pointer is evaluated.

[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);

?

+3
source share
5 answers

This is a standalone executable protected bit of code. Let me break it:

(function(window, PhotoSwipe){
  ...
}(window, window.Code.PhotoSwipe));

In parentheses, our code will be executed by itself, without any additional links.

window window.Code.PhotoSwipe, . , PhotoSwipe window.Code.PhotoSwipe. window, , window.

, addEventListener, , :

function myFunc() {
  var options = {},
      instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );
}
document.addEventListener('DOMContentLoaded', myFunc, false);

: , , addEventListener .

addEventListener . DOMContentLoaded. document. , , , myFunc.

false . , DOM. Capturing, DOM . Bubbling, DOM . false , bubbling.

myFunct, , DOMContentLoaded document, , options. , .

-, attach PhotoSwipe. - . DOM , #Gallery a, "". :

<div id="Gallery"><a href="#">Foo</a></div>

<div id="Gallery">
  <div class="picture">
    <a href="#">Open</a>
  </div>
  <div class="picture">
    <a href="#">Open</a>
  </div>
</div>

, . , PhotoSwipe , .

+3

, . window.Code.PhotoSwipe PhotoSwipe.

window , this, ( window) .

+2

- . - . , , .

0

:

(function(window, PhotoSwipe){
    document.addEventListener('DOMContentLoaded', function(){
        var options = {},
            instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'),
                                      options );
        }, false);
}(window, window.Code.PhotoSwipe));

This creates a function with two arguments (window and PhotoSwipe) that adds an event listener - a second (internal) function, and then immediately calls an external function with value windows and window.Code.PhotoSwipe as arguments.

What for? Javascript is not very suitable for separating areas unless you paste the code inside a function. Therefore, inside the main function in the sample, PhotoSwipe can only refer to the second argument passed to.

0
source

All Articles