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".
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With