Creating a local jQuery.data key reference

I am testing on jQuery.data() , and I am trying to create a local link to a specific data key, which I hope can change locally and still affect the "external". I think it would be better with an example, because of the half-long code I posted it on jsFiddle, and not here:

http://jsfiddle.net/esbenp/p4kt2/22/

The conclusion I hope for is:

 {1: {length: 1}, total: 1} 

but only the increase in the local variable affects the length property:

 {1: {length: 1}, total: 0} 

what should I do?

+3
scope jquery reference
Apr 22 '11 at 20:11
source share
2 answers

If you store an object (or array) in .data() , then you actually store a reference to it, so if you do:

 var obj = { key: 'value' } $(el).data('obj') = obj; obj.key = 'new value'; 

$(el).data('obj').key will also be new value , because it is the same object.

However, if the stored value is a simple type (for example, a number or a string) in which its copy will be stored:

 var n = 5; $(el).data('obj') = n; n++; 

$(el).data('obj') will still be 5.

+5
Apr 22 2018-11-21T00:
source share

I'm not going to lie - this code is incredibly confusing. Is there a reason you need to use all these self-executing functions? It seems (at least to this layman) that you could code this in a much simpler way to achieve your goal.

In any case, I'm not sure if this is the answer you are looking for, but I just stopped the debugger inside AddError so that I could understand its scope and what was available. So, all you have to do to return the result you want is the following:

http://jsfiddle.net/qN7wF/2/

 functions = { AddError: function() { console.log(total); $(container).data('errors').total++; errors.length++; }, 

But given the context ... I suppose there should be more in the game.

+2
Apr 22 2018-11-11T00:
source share



All Articles