Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active April 24, 2024 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/666befec19ca9e5ecb72e46346ede148 to your computer and use it in GitHub Desktop.
Save Kcko/666befec19ca9e5ecb72e46346ede148 to your computer and use it in GitHub Desktop.
/* 1 */
var item = document.getElementById("hi");
console.log(item);
item.data = {getType: function(){return this.TYPE},TYPE:"winner"};
var out = item.data.getType();
console.log("out", out);
var two = document.getElementById("hi")
console.log("should say 'winner': ", two.data.getType());
/* 2 */
window.$ = {
data: function(obj, key, val) {
if(!obj) {
return this._data;
} else if(!key) {
if(!(obj in this._data)) {
return {};
}
return this._data[obj];
} else if(arguments.length < 3) {
if(!(obj in this._data)) {
return undefined;
}
return this._data[obj][key];
} else {
if(!(obj in this._data)) {
this._data[obj] = {};
}
this._data[obj][key] = val;
}
},
_data: {}
};
$.data(document.body); // Returns {} because no data has been set for this object
$.data(document.body, 'lastUpdate', new Date());//Sets 'lastUpdate' of obj to current time
$.data(document.body, 'lastUpdate'); // Gets previously set time
$.data(document.body); // Gets object of all data, including 'lastUpdate' time
$.data(document.body, 'nonexistant'); // Returns undefined because property was never set
$.data(); // Returns all metadata
/* 3*/
/** A storage solution aimed at replacing jQuerys data function.
* Implementation Note: Elements are stored in a (WeakMap)[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap].
* This makes sure the data is garbage collected when the node is removed.
*/
window.dataStorage = {
_storage: new WeakMap(),
put: function (element, key, obj) {
if (!this._storage.has(element)) {
this._storage.set(element, new Map());
}
this._storage.get(element).set(key, obj);
},
get: function (element, key) {
return this._storage.get(element).get(key);
},
has: function (element, key) {
return this._storage.has(element) && this._storage.get(element).has(key);
},
remove: function (element, key) {
var ret = this._storage.get(element).delete(key);
if (!this._storage.get(element).size === 0) {
this._storage.delete(element);
}
return ret;
}
}
var myElement = document.getElementById("myId");
dataStorage.put(myElement, "myKey", "myValue");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment