1

I'm making a jQuery plugin in which one each elements should have their own variables. I believed the correct way to do so was:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>test 1</div>
<div>test 2</div>
<script language="javascript">
$.fn.menu = function(options) {
    var defaults = {i : 0};
    this.each(function(){
        var parameters = $.extend(defaults, options); 
        $(this).on("click", function(event){parameters.i++;alert(parameters.i);});
    });
};
$("div").menu();
</script>

but it doesn't work: the parameters object is global and so shared between all elements for which the plugin is called.

What's wrong in this example?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Comode
  • 25
  • 3
  • It isn't global but you are facing closure issue... – A. Wolff Dec 17 '15 at 14:47
  • Why do you want to use a closure here? It's not a loop, and there's nothing to do with the answered question you link ! Moreover, the goal is to show the last value of i... it's the opposite of what a closure is means to do. – Comode Dec 17 '15 at 14:54
  • `each` is looping method – A. Wolff Dec 17 '15 at 14:55
  • your point. However, parameters is defined in the each(). Couldyou please remove the "already answrred elsewhere" ? the question is different and the answer given doesn't answer to this one. – Comode Dec 17 '15 at 14:58
  • @Comode You are correct, your issue is regarding you are extending same object, use: `var parameters = $.extend({}, defaults, options);` – A. Wolff Dec 17 '15 at 15:06
  • Maybe more relevant dupe: http://stackoverflow.com/questions/8332458/merge-loops-with-jquery-extend-last-value-is-always-the-same – A. Wolff Dec 17 '15 at 15:11
  • It works ! Thank you very much ! – Comode Dec 17 '15 at 15:14

1 Answers1

0

Using var parameters = $.extend(defaults, options);, parameters is reference to (extended) defaults object.

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend().

You need to create a new object reference, passing empty one to jQuery extend() method:

var parameters = $.extend({}, defaults, options);

This is equivalent to:

var parameters = $.extend(JSON.parse(JSON.stringify(defaults)), options); 
A. Wolff
  • 74,033
  • 9
  • 94
  • 155