Last active
December 27, 2015 09:09
-
-
Save rodneyrehm/7302213 to your computer and use it in GitHub Desktop.
@helloanselm: simple off-dom storage added to dom nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.