Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.data() namespace

How can I avoid conflicts with other jQuery plugins using $.data()?

I was thinking I could use a single key to store my data like

$(el).data('myplugin', { foo: 'a', xyz: 34});

and access it like $(el).data('myplugin').foo etc.

But how can easily change a value, without overriding the whole data? Like changing the value of "foo".

like image 531
Alex Avatar asked May 03 '12 18:05

Alex


2 Answers

Why not using

$(el).data('myplugin.foo')

and

$(el).data('myplugin.xyz')

?

So if you don't need to access more than one value at the same time, you avoid useless indirections and tests.

like image 140
Denys Séguret Avatar answered Oct 14 '22 16:10

Denys Séguret


Just change the property you want to change.

http://jsfiddle.net/rQQdf/

var el = $("<div />");    
el.data("myPlugin",{ foo: "foo" });
console.log(el.data("myPlugin").foo); // foo
el.data("myPlugin").foo = "bar";
console.log(el.data("myPlugin").foo); // bar

As far as namespace conflicts, one solution is to generate a timestamp at runtime (when the plugin is defined) and use that timestamp in your namespace. It still isn't 100% protected against conflicts in the fastest browsers, but it gets pretty close.

like image 40
Kevin B Avatar answered Oct 14 '22 16:10

Kevin B