JQuery.data () namespace

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

I thought I could use one key to store my data, for example

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

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

But how easy is it to change the value without overriding all the data? Like changing the value of "foo".

+7
source share
3 answers

Why not use

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

and

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

?

So, if you do not need to access multiple values ​​at the same time, you avoid unnecessary directions and tests.

+7
source

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 

Regarding namespace conflicts, one solution is to create a timestamp at runtime (when the plugin is defined) and use that timestamp in your namespace. It is still not 100% protected from conflicts in the fastest browsers, but it is pretty close.

+7
source

I personally use a hyphenated naming convention that prefixes class names, identifiers, data properties, etc. with the abbreviated identifier of the object to which the code belongs, and one for the functionality area.

If I were working on a graphics program for Foo, my prefix could be as follows:

 foo-chart- 

This allows me to create unique company identifiers for companies and unique areas of code (to avoid collisions with other developers in other areas of functionality).

Thoughtful example:

 <button id="foo-chart-refresh" class="foo-chart-interact" data-foo-chart-last="201205031421">Refresh Chart</button> <script type="text/javascript"> var lastRefresh = $('#foo-chart-refresh').data('fooChartLast'); // see docs on .data() for case/hyphenation handling </script> 

I believe that using a hyphen works well almost anywhere where my identifiers will be needed - either as a value or attr markup name, or code, etc. You can use any char that suits your needs ( . Very often)

+3
source

All Articles