Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain this javascript pattern used in the Twitter Bootstrap plugins to me?

I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:

!function($) {
  // code here

  // plugin definition here

} ( window.jQuery || window.ender);

This looks like a variation of the immediately executing anonymous function (anonymous closure):

(function($) {
  // code here

}(jQuery));

Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?

Thanks!

like image 777
Peter Avatar asked Jan 20 '12 23:01

Peter


People also ask

What is Bootstrap JavaScript plugins?

Bootstrap provides custom events for most plugins' unique actions. Generally, these come in an infinitive and past participle form - where the infinitive (ex. show ) is triggered at the start of an event, and its past participle form (ex. shown ) is triggered on the completion of an action. As of 3.0.

What are bootstrap plugins?

Bootstrap comes bundled with 12 jQuery plugins that extend the features and can add more interaction to your site. To get started with the Bootstrap's JavaScript plugins, you don't need to be an advanced JavaScript developer.

How do I know if bootstrap is used?

We can check Bootstrap-specific method is available or not. Syntax: var bootstrap = (typeof $(). "Bootstrap-specific method" == 'function');

Which one of the following features is provided by bootstrap?

Explanation: Bootstrap's JavaScript plugins, you don't need to be an advanced JavaScript developer. By utilizing Bootstrap Data API, most of the plugins can be triggered without writing a single line of code.


1 Answers

//  |---1. makes the function as part of an expression 
//  |                             so it can be immediately invoked
//  v
    !function($) {
//            ^
//            |___4. references what was passed, window.jQuery or window.ender

      // code here

      // plugin definition here

    } ( window.jQuery || window.ender); // <---2. immediately invoke the function 
//         ^                ^
//         |________________|_______3. pass window.jQuery if it exists, 
//                                                      otherwise window.ender
like image 128
2 revsuser1106925 Avatar answered Oct 09 '22 22:10

2 revsuser1106925