ElementStore: jQuery.data standalone implementation
jQuery.data() allows you to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. It's very useful, unfortunately I don't use jQuery and sourcing 7000 lines of JavaScript just to get this functionality isn't an option. So I implemented a standalone jQuery.data that can be used in other libraries.
Usage of ElementStoreThe API isn't the same as jQuery.data, since I think the API of jQuery.data is too implicit. It would be very easy to emulate jQuery.data, but this is an exercise for the reader ;-) Usage: ElementStore.set(elm, "meaning of life", {42: 42})
ElementStore.get(elm, "meaning of life")
ElementStore.remove(elm, "meaning of life") //delete just one key
ElementStore.remove(elm) //delete all element keys
Implementation of ElementStoreElementStore lives on github. But for the reference, here is the implementation: ElementStore = {
storage_dict: {},
uuid: 1,
expando: 'ElementStore' + (new Date).getTime(),
get: function(elm, key) {
return ElementStore.getStore(elm)[key] || null;
},
set: function(elm, key, value) {
ElementStore.getStore(elm)[key] = value;
return value;
},
remove: function(elm, key) {
if(key != undefined) {
var store = ElementStore.getStore(elm);
if(store[key])
delete store[key];
}
else {
var elm_id = elm[ElementStore.expando];
if(elm_id) {
delete ElementStore.storage_dict[elm_id];
delete elm[ElementStore.expando];
}
}
},
getStore: function(elm) {
var expando = ElementStore.expando;
var storage_dict = ElementStore.storage_dict;
var elm_id = elm[expando];
if(!elm_id) {
elm_id = elm[expando] = ElementStore.uuid++;
storage_dict[elm_id] = {};
}
return storage_dict[elm_id];
}
}
Announcements
·
Code
·
Code improvement
·
JavaScript
•
14. May 2010
|
|