Noah Blumenthal's Blog

July 27, 2009

jQuery $.extend() method with plugin called multiple times (note to self: RTFM!)

Filed under: Uncategorized — noahblu @ 4:22 pm

 

jQuery’s $.extend() method is used to merge two (or more) objects.  It’s very useful in plugin development since it can be used to merge user defined options with default options for a plugin.  I ran into an issue today trying to debug a plugin I wrote (jquery inline row editor) whereby settings were getting all screwed up if it was used multiple times on a page (ie a page with multiple editable tables).  I’m ashamed to say it, but it took me a while of debugging before realized what the issue was.  Note to self: RTFM!!!

Take the following snippet:

   1: $.fn.inplacerowedit = function(options) {

   2:     var ops = $.extend($.fn.inplacerowedit.defaults, options);

   3:     .....

   4: }

Now what I didn’t take into account is that the $.extend() method doesn’t just spit out a merged object based on all the parameters, it merges all objects sent in as parameters into the first parameter.  So in this example above, ops == $.fn.inplacerowedit.defaults which itself is a combination of what it started out as and the options parameter.  Well that now makes sense why things got screwed up when this was called multiple times, huh?

So the solution was to set the first parameter of the $.extend() method to a blank object {} and have jQuery append EVERYTHING to that and set THAT to ops like so:

   1: $.fn.inplacerowedit = function(options) {

   2:     var ops = $.extend({}, $.fn.inplacerowedit.defaults, options);

   3:     .....

   4: }

OR I suppose you could just declare ops and then use that as the first parameter.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: