javascriptjqueryoopjquery-pluginsjquery-data

Why use $.data instead of assigning properties to "this"?


I noticed a lot of jQuery plugin developers use the $.data function to store the state of some type of action.

$.data(this, 'playing', true);

instead of just assigning a property to the plugin object instance:

this.playing = true;

What's the deal here? Are there some benefits on using $.data ?


Solution

  • According to the docs, it avoids memory leaks with circular references.

    Also, .data() does not conflict with existing methods and properties of the HTMLElement, being more future proof.


    By future proof, I mean, a simple example would be storing the play state of an audio/video element in its playing property, your code works and all is fine. Then tomorrow, the WHATWG decides to add a playing property to the HTMLMediaElement DOM interface and boom! Your code breaks or has unexpected side effects.

    This is of course just a dumb example to illustrate the possibility for future conflicts, in the use case above you'd normally just read the paused property of the element.

    Another example would be setting the value property -- you test it with a span and it works fine, then you ship the code and another developer tries to call the plugin on an input element, it will conflict with the value of the input. This kind of problem is easily avoided with $.data.

    Talking in the general sense of storing metadata in a custom property of a DOM element, there is always a small probability of future conflict. Even though the odds are often very low, it is nice to feel more future proof and have one less thing to worry about.