Sammaye
Sammaye

Reputation: 43884

How to use element specific settings in a jquery plugin?

I have code that looks like:

(function($, window, undefined){
    var options, methods = {
        init : function(opts){

            options = $.extend({}, {
                width   : 800,
                height  : 600,
            }, opts);

            return this.each(function(){
                data = $(this).data('prodigal');
                if(!data){
                    $(this).data('prodigal', options).on('click', openl);
                }
            });
        },
    },
    openl = function(){
        console.log(options);
    };


    $.fn.prodigal = function(method) {
        // Method calling logic
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.prodigal' );
        }
    };
})(jQuery)

And I call it like:

$('.view_title_images').prodigal({width: 500});
$('.glglg').prodigal({ width: 600 });

The problem is when I output the options in openl I actually get both selectors showing a width setting of 600.

Up until recently I stored element specific info on the elements data tag: $(this).data('prodigal', options) and then acessed that data in every function I made so that openl would have a line at the top that goes like: options = $(this).data('prodigal').

I did try and use public methods instead but I couldn't seem to bind those public methods in the $(this).data('prodigal', options).on('click', openl); line, it kept producing errors.

Should I still be trying to store my settings in my elements data tag or is there something I am missing about building jQuery plugins? How do I manage settings in a plugin?

This doesn't seem to be clearly covered by previous topics I have searched for.

Upvotes: 1

Views: 285

Answers (1)

Sammaye
Sammaye

Reputation: 43884

To answer this to a degree, as @Matt says:

Storing options in data() is the usual approach.

And I have now come to the realisation I was doing nothing wrong.

The reason for this question was because, in the wild, I have seen many plugins created in many ways.

Due to a comment that is kind of linked: Difference in $.extend calls in a plugin? I have been able to get hold of a set of "good" design patterns that I can use to suite my needs (that are not in the documentation): http://jqueryboilerplate.com/ as kindly provided by @Marcus in the linked comment.

Upvotes: 1

Related Questions