Hash by object reference in javascript -
anyone ever need hash object reference in javascript?
maybe want group children of uls hash of dom nodes, or attributes instances of constructed objects, or many other things.
i have read this , don't want use weakmaps until they're stable.
the way can think storing parents in array , enforcing reference uniqueness there, hashing index of reference in array. (example finding common ul parents of lis):
var lis = document.getelementsbytagname('li'); // objects var parent, key, li; (var i=0; i<lis.length; i++ ) { // every li storeitembyparent(lis[i], lis[i].parentnode); } var parents = []; var itemsbyparent = {}; function storeitembyparent (item, parent){ var key; // parent exist? if so, use index hash key (var j=0; j<parents.length; j++) { if(parents[j] === parent) { key = j; break; } } // new parent? if so, track , use index hash key if (key == undefined) { parents.push(parent); key = parents.length; } // finally! lis in hash parent "id". itemsbyparent[key] = itemsbyparent[key] || []; itemsbyparent[key].push(item); } is there better way store attributes or children or other things attached object instance without adding them properties of object itself?
you've pretty got right approach there, though i'd wrap nicely behind interface, complete own add , find methods.
you can coding using <array>.indexof, supported in modern browsers , polyfilled when needed.
there downside approach however:
should element removed dom, element won't garbage collected because array still holding onto reference it.
while isn't show stopper, of course, worth keeping in mind.
there is, however, totally different approach can take well. may not better -- different.
please forgive minor errors in code, typing freehand:
function elementdatahash = {}; function setelementdata(el, data) { var hash = el.getattribute("data-element-hash"); if !(hash) { // http://stackoverflow.com/questions/6860853/generate-random-string-for-div-id hash = generaterandomstring(); el.setattribute("data-element-hash", hash); } elementdatahash[hash] = data; } function getelementdata(el) { var hash = el.getattribute("data-element-hash"); return elementdatahash[hash]; }
Comments
Post a Comment