Creating a jQuery plugin with configuration settings

I am using the following project to create jQuery plugins. I'm pretty sure I got the concept from the jQuery main page, however it is no longer published there.

I recently tried to access a variable settingsin a method (i.e. someOtherMethod ()) different from the method init(), and experienced an error because settingsit was not defined. I see the reason, because it is settingsisolated from the method init().

If I move settingsoutside this method, I could access it from different methods, however, each instance, when the plugin is applied, will not have its own unique parameter variable, which is unacceptable. For example, it $('#id1, #id2').myPlugin({x:111});must have a common variable settings, but it $('#id1').myPlugin({x:111}); $('#id2').myPlugin({x:222});must have its own unique configuration variable.

Given the design pattern below as a starting point, how can I access a variable settingsfrom all the methods associated with the plugin, but does it have a unique variable each time it is used settings?

(function( $ ){

    var defaults={
        x : 123,
        y : 321
    };
    // var settings={}; //Should settings be defined here???

    var methods = {
        init : function( options ) {
            var settings = $.extend(defaults, options  || {});
            //settings = $.extend(defaults, options  || {}); //Should settings just be updated and not defined here?
            return this.each(function(){
                //whatever
            });
        },

        someOtherMethod : function() {
            return $(this).each(function(){
                //do whatever and use settings variable as applicable
            })
        },
    };

    $.fn.myPlugin = function(method) {
        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.myPlugin' );
        }    
    };

}( jQuery ));

$('#id1, #id2').myPlugin({x:111});  //Sets x=111 in settings for both
$('#id3').myPlugin({x:333});        //Sets x=333 in settings.
$('#id3').myPlugin('someOtherMethod');  //Will have access to x=333 in settings.
+4
source share
3 answers

, . - jQuery.data, . , , , , .

.each someOtherMethod , jQuery.data .

, , , :

var settings = $.extend(defaults, options  || {});

:

var settings = $.extend({}, defaults, options  || {});

defaults .

internalPrefix '_myPlugin' , jQuery.data. , , -, an , .

:

(function( $ ){

    var defaults={
        x : 123,
        y : 321
    };
    //A variable to save the setting data under.
    var internalPrefix = '_myPlugin';

    var methods = {
        init : function( options ) {
            return this.each(function() {
                //Setup the settings object.
                var settings = $.extend({}, defaults, options || {});
                //Save the settings to the element.
                $(this).data(internalPrefix, settings);
            });
        },

        someOtherMethod : function() {
            return this.each(function() {
                //Get the existing settings.
                var settings = $(this).data(internalPrefix);
                //Example:
                $('<code></code>').text(JSON.stringify(settings)).appendTo(this);
            })
        },
    };

    $.fn.myPlugin = function(method) {
        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.myPlugin' );
        }
    };

}( jQuery ));

//Initialize the plugin different ways.
$('.group-1').myPlugin();
$('.group-2').myPlugin({
    x : 42,
    y : 1337
});

//Cal the methods on those different ways.
$('p').myPlugin('someOtherMethod');
<p class="group-1">group 1</p>
<p class="group-1">group 1</p>
<p class="group-2">group 2</p>
<p class="group-2">group 2</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Hide result
+4

, {} $.extend()

, , , , :

var object = $.extend({}, object1, object2);


defaults methods, settings init

var settings = $.extend({}, methods.defaults, options || {});

this .data() settings .each()

return this.data(settings).each(function() {})

settings ; $(this).data(), defaults, options $.fn.myPlugin, defaults, options $.fn.myPlugin


(function($) {

  var defaults = {
    x: 123,
    y: 321
  };

  var methods = {
    init: function(options) {
      // extend `methods.defaults` with `options`
      var settings = $.extend({}, methods.defaults, options || {});
      return this.data(settings).each(function() {
        //whatever
        console.log("init", this.id, $(this).data());
      });
    },

    someOtherMethod: function() {
      return $(this).each(function() {
        //do whatever and use settings variable as applicable
        console.log("someOtherMethod", this.id, $(this).data());
      })
    },
  };
  // set `defaults` as property of `methods`
  methods.defaults = defaults;

  $.fn.myPlugin = function(method) {
    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.myPlugin');
    }
  };

}(jQuery));

$('#id1, #id2').myPlugin({
  x: 111
});
$("#id1").myPlugin({
  y: 222
});
$("#id2").myPlugin({
  y: 333
});
$("#id2").myPlugin("someOtherMethod");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="id1"></div>
<div id="id2"></div>
Hide result

jsfiddle http://jsfiddle.net/z28wwnLh/1/

+1

Just a quick punch, but won't it work? or did i completely skip this item?

(function ($) {

        var defaults = {
            x: 123,
            y: 321
        };

        $.fn.myPlugin = {
            init: function (opts) {
                var settings = $.extend(defaults, opts || {});
                $.each(settings, function (a, b) {
                    console.log(a, ':', b);
                });
            },

            someOtherMethod: function (opts) {
                var settings = $.extend(defaults, opts || {});

                $.each(settings, function (a,b) {
                    console.log(a,':', b);
                });
            }
        };
    }(jQuery));

    $('#id1, #id2').myPlugin.init({ x: 111 });  //Sets x=111 in settings for both
    $('#id3').myPlugin.init({ x: 333 });        //Sets x=333 in settings.
    $('#id3').myPlugin.someOtherMethod({ x: 223 });
    $('#id1').myPlugin.someOtherMethod({ a: 223 });
0
source

All Articles