13 Mar, 2009

Published at 07:22AM

Tagged with javascript, jquery, plugin, programming, and tips

This post has 4 comments

Deeply extending jQuery options

One thing I love about jQuery is its plugin capabilities. And one thing I like to try and do with the plugins I write is to make them semi-customizable. This usually means passing in some options that get merged with defaults. For instance, this is a common pattern for me:

1
2
3
4
5
6
7
8
9
(function($) {
  $.fn.somePlugin = function(options) {
    var defaults = { ... }
    
    var settings = $.extend(defaults, options)
    
    // ...
  }
})(jQuery)

The passed in options overwrite the defaults. But I learned something yesterday that takes this a bit further, and allows me to have even more flexibility with my plugins. And that something is $.extend() with a deep copy.

Changing:

1
var settings = $.extend(defaults, options)

To:

1
var settings = $.extend(true, defaults, options)

Tells $.extend() to perform a deep copy merge. What does that mean? Well it means that I can generically handle a whole slew of attributes, for example, without having to define elementClass: 'wrapper' and so forth.

Using the example above, with a deep copy, my defaults may now look like this:

1
2
3
4
5
6
7
var defaults = {
  elementAttributes: {
    id: 'some-id',
    class: 'some-class'
  },
  // ...
}

And then I can pass the entire elementAttributes to the element in question:

1
$(this).attrs(settings.elementAttributes)

That’s much better since I don’t have to explicitly define/handle each possible attribute that I may want to add or modify later on.

Maybe you’ll find this useful, maybe you won’t. Or maybe you already knew. At any rate, it truly is a better way of making your plugins (and such) more flexible.

Comments

Alexander Sunday, 15 Nov, 2009 Posted at 03:59AM

Thanks, Ryan, very nice,clear and useful article. Now I will develop my jquery plugins much faster.

joseh Monday, 04 Jan, 2010 Posted at 01:14PM

deep copy, shallow article

Ryan Monday, 04 Jan, 2010 Posted at 03:52PM

Ha, sweet. Now with an insightful comment to accompany it!

Chris Monday, 13 Sep, 2010 Posted at 02:37PM

Big thanks for this article! Very usefull because I had problems with deep options and your resolution is very easy :D

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch