Ban
Ban

Reputation: 119

Why store the function on the element using data()?

I am trying to understand some code from the Swipebox plugin.

There is a function declared.

$.swipebox = function( elem, options ){
   // plugin Jquery codes..
}

Now this codes below I really do not understand. What is the main purpose of this code? Why does it save function to the element?

$.fn.swipebox = function( options ) {

    if ( ! $.data( this, '_swipebox' ) ) {
        var swipebox = new $.swipebox( this, options );
        this.data( '_swipebox', swipebox );
    }
    return this.data( '_swipebox' );
};

Why not just run the swipebox(this, options);?

$.fn.swipebox = function( options ) {
   $.swipebox(this, options);
};

Also I do not understand of using $.swipebox instead of using swipebox when function is declared.

Upvotes: 1

Views: 93

Answers (1)

jfriend00
jfriend00

Reputation: 707456

The way swipebox is doing it avoids declaring any new global variables.

Their constructor function is $.swipebox() and their jQuery method is $.fn.swipebox() which can be invoked on a jQuery object as $(".selector").swipebox(...).

this.data( '_swipebox', swipebox );associates the swipeBox object (created by the swipeBox constructor) with the actual DOM object so when any sort of event happens on the DOM object, some code can find the swipebox object that already exists for that DOM object (again without creating any new global variables to keep track of this). This way, the DOM object points to the swipebox object (via the .data() association) and the swipebox object contains the relevant DOM object so each can get to the other as needed.

Upvotes: 1

Related Questions