For quite some time now I had intention to open this discussion because of increasing tendency of using data/event API on native objects.
Why this is a problem?
Well, the current $.data implementation is optimized for host objects only, and not for native objects too.
In fact, it uses a cache object to store all related data and an expando with numerical values to keep references.
The need of such solution is unquestionable and it fits well because elements are normally "eliminated" by using .remove() that also cleans respective data. Native objects, in other hand, are not "eliminated" with such call, and related data exists until the window is closed.
Of course, this problem also exists with the event API, that uses data API to store handlers...
Solution AProbably the easiest fix would consist on storing data as expando property of native objects.
- // ...
- if ( elem.nodeType ) {
- cache[ id ] = dataObject;
- elem[ expando ] = id;
- } else {
- elem[ expando ] = dataObject;
- }
- // ...
Inheritance problemUnfortunately that fix would not be sufficient once the object inheritance will become mainstream.
- var objA = {};
- var objB = Object.create( objA );
- $.data( objA, "foo", "bar" );
- $.data( objB, "foo" ) // => "bar" - ok, I suppose..
- // ..but..
- $.data( objB, "foo", "barB" );
- $.data( objA, "foo" ); // => "barB" - oh noo..
- $.data( objA ) === $.data( objB ) // => true - ...objA and objB have the same data object!
If you think that the returned value at line 5 would be 'undefined', then using hasOwnProperty on reading objectData of native objects will resolve the problem at lines 7-9. Otherwise, keep reading.
Solution BTo inherit values of parent objects, we have to store values in native objects itself!
- // ...
- if ( elem.nodeType ) {
- dataObject[ name ] = value;
- } else {
- elem[ expando +"_" + name ] = value;
- }
- // ...
The only lack of this solution is that we can not return the data object of the native object, because it doesn't exists!
- $.data( objA ); // => null? there is no data objects for native objects!
But I think it's not a big deal...
EDIT: Reconsidering the first solution...