I believe this question relates to this: How does the init function work in plugins? and whoever can answer this can probably answer that.
I noticed something about jQuery, if I call my plugin like:
$('.view_title_images').prodigal({width: 500});
$('.glglg').prodigal({ width: 600 });
And then, in my init function I extend with:
options = $.extend({}, options, opts);
and add that to each element: $(this).data('prodigal', options) in the selector. I get the correct width value for each element (500 for one and 600 for the other) later on when I call another function, open on the click of the element.
However if I do:
options = $.extend(options, opts);
For both selectors, despite being called separately, I get 600. I test this by doing, in my open function:
console.log($(this).data('prodigal'));
I know that not extending to an empty object will override the object for that selector/global object but why is this happening on the data of each selector?
Even though @Marcus’ answer is a good one and it shows a good setup to plugins that will actually avoid this confusion I thought I would place this answer because it just answers the question a little better.
I am witnessing, like in PHP, a copy on write scenario for memory management here: What is copy-on-write? whereby my init function, as displayed in this fiddle: http://jsfiddle.net/Sammaye/65XLy/1 suffers from the static options object being referenced to each of the calls. So both of:
Reference the same position in memory for the
optionsobject in the plugin since the data assignment is not copy on write safe:This is proven since if you change this line in the fiddle to:
It actually works the same as
var options = $.extend({}, options, opts);whereby it does copy to a new empty object on extend which in copy on write would trigger a copy.That is why I am seeing this, because the
datain each of the elements is actually a reference to the static objects (plugins)optionsobject.As an added note I actually found this soon after posting this answer: http://my.opera.com/GreyWyvern/blog/show.dml/1725165 whereby the author states:
Which explains my problem perfectly.