From b99f616489eff1889a8c4e115c93dd2bfbc1ddfd Mon Sep 17 00:00:00 2001 From: Thomas Wilburn Date: Sat, 26 Jul 2014 14:49:09 -0700 Subject: [PATCH] Add the elementData util library (still not in stable, though). --- js/util/elementData.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 js/util/elementData.js diff --git a/js/util/elementData.js b/js/util/elementData.js new file mode 100644 index 0000000..702fa64 --- /dev/null +++ b/js/util/elementData.js @@ -0,0 +1,39 @@ +define(function() { + + /* + + Storing JS data on HTML elements has, in the past, been a likely source of + memory leaks one way or the other. In this module, we create a set of + matching WeakMaps for connecting data to DOM and vice versa. The dom2 module + uses this to emulate jQuery's data() method, and other modules can import this + to ask for an element given a JS object (such as a tab instance). + + */ + + var elements = new WeakMap(); + var objects = new WeakMap(); + + return { + get: function(key) { + var map = key instanceof HTMLElement ? elements : objects; + return map.get(key); + }, + set: function(key, value) { + var isDom = key instanceof HTMLElement; + var forward = isDom ? elements : objects; + var reverse = isDom ? objects : elements; + forward.set(key, value); + reverse.set(value, key); + }, + "delete": function(key) { + var isDom = key instanceof HTMLElement; + var forward = isDom ? elements : objects; + var reverse = isDom ? objects : elements; + var data = forward.get(key); + forward.delete(key); + reverse.delete(data); + } + } + + +}); \ No newline at end of file