views:

45

answers:

2

I'm working on a jQuery plugin and can't seem to override the default settings, here's a snippet of the plugin.

        $.Auction  = {

        defaults: {
            parentId: '#span',
            bidButtonClassName: '.live_bid'
        }
    };


    $.setAuction = function(options){

        startAuction();

    }

    function startAuction(){

            var options = $.extend({}, $.Auction.defaults, options);
            alert(options.parentId);

    }



    $.setAuction({parentId: '#div'});

Basically I'm trying to override the parentId value at the bottom, but it always alerts the value #span. Any ideas what I'm doing wrong? Thanks!

+1  A: 

You're passing {parentId: '#div'} as an argument to $.setAction, but you're not actually using it. You want to do something like this:

$.setAuction = function(options){
    startAction(options);
}

function startAction(options){
        options = $.extend({}, $.Auction.defaults, options);
        alert(options.parentId);
}

Edit: @TmEllis suggests a better way of implementing this functionality, but it can be made better still by making the defaults themselves customizable:

(function($)
{
    $.fn.setAuction = function(options)
    {   
        options = $.extend({}, $.fn.setAuction.defaults, options);
        return this.each(function()
        {
            alert($(this).id);
        });
    };

    $.fn.setAuction.defaults =
    {
        bidButtonClassName: '.live_bid' 
    };
})(jQuery);

See this article for a more complete discussion of how to write good jQuery plugins.

Will Vousden
Ahh.. okay I tried this, but now if I don't define the parentId within setAuction({}), it comes up as undefined.
Dave
@Dave: Can't really help you without more specific information. It works fine for me.
Will Vousden
+1  A: 

I think you need to change the code a bit.

$.fn.setAuction would be better than $.setAuction (They do two different things)

as you could do:

$("#span").setAuction ({bidButtonClassName:"classname"});

and pass the element to it as a selector not as the plugin options (unless it needs to be in options)

Your plugin code might look something like then:

(function($) {

    $.fn.setAuction  = function(options) {   
        var defaults = {
          bidButtonClassName: '.live_bid' 
        };


      var options = $.extend(defaults, options);
      //or to preserve defaults
      var options = $.extend({}, defaults, options);

      return this.each(function() {
          obj = $(this); //"#span"
          alert(obj.id);


      });
   };
})(jQuery);
+1 for a more idiomatic approach.
Will Vousden