0

I'm starting to become a plugin creator and don't fully have the hang of it. One problem is I would like to make an default where you have two numbers. And I need to be able to apply them to the code.

What I mean is like this:

var defaults = {
numbers: [1, 2]
}

I like how the jquery team did it with draggable:

$('#drag').draggable({
grid: [1, 100]
});

Which is something I would like to do. Any Idea how?

Shawn31313
  • 5,978
  • 4
  • 38
  • 80

2 Answers2

1

One nice way to do this is to use $.extend, which merges the contents of two or more objects together into the first object:

(function($) {
    $.fn.foobar = function(options) {
        var settings = {
            numbers: [1, 2]
        };
        $.extend(settings, options);

        /* continue with plugin code. */           

        alert(settings.numbers[0] + " " + settings.numbers[1]);
    };
})(jQuery);

Now settings is a combination of the user-specified options and the "default" options. See this section of the plugin authoring tutorial for more information.

Example: http://jsfiddle.net/2Djya/

P.S: A good resource for figuring out how plugins work is the jQueryUI source itself.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

simplified plugin code:

$.fn.yourPlugin = function( conf ){
    var config = $.extend({
        someVar : 'default'
        ,   foo : 'anotherDefault'
    }, conf );

    return this.each( function(){
        // do stuff with $( this ) and config
    } );
};

the $.extend will copy any params from conf which is passed in onto the object you create that sets the defaults.