Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Last active December 27, 2015 09:09
Show Gist options
  • Save rodneyrehm/7302213 to your computer and use it in GitHub Desktop.
Save rodneyrehm/7302213 to your computer and use it in GitHub Desktop.
@helloanselm: simple off-dom storage added to dom nodes
(function() {
var storage = {};
var counter = 1;
function nodeId(node) {
return node._dataId || (node._dataId = counter++ );
}
function nodeData(node, key, value) {
var id = nodeId(node);
var data = storage[id] || {};
if (key === undefined) {
// read all data
return data;
} else if (typeof key === 'string') {
if (value === undefined) {
// read specific key
return data[key];
}
// set specific key
data[key] = value;
storage[id] = data;
return null;
}
// set value object
storage[id] = value;
return null;
}
// expose on dom nodes
Node.prototype.myData = function(key, value) {
return nodeData(this, key, value);
};
})();
// USAGE:
document.body.myData('key', 'value');
console.log(document.body.myData('key'));
@rodneyrehm
Copy link
Author

WARNING

This code is meant as an example to illustrate how data can be saved on a DOM element without storing the data using slow DOM API. This example is missing functions to removeData() and does not make use of Mutation Observers to clean the storage once an element was removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment