Any danger when using html object as "name" attribute in javascript object?
when linking javascript objects to html objects
// javascript element
var element = { tag:'input', name: 'email', value:null, dom: null,
verifyFunc: function() {...}, postFunc: function() {...},
rcdElement: some_element }
// lookup javascript element from dom
var doms = {};
// create html element for dom
var item = document.createElement(element.tag);
item.name = element.name;
...
// cross-link
doms[item] = element;
element.dom = item;
// using it in generic "onchange" trigger
function changeTrigger(e) {
var el = doms[e.target];
....
};
Are there any dangers lurking in this approach?
source to share
Object keys are strings. So when you try to use a DOM object as a key object, it calls toString()
on the DOM object and uses it as a key. toString()
on DOM objects, non-unique things like this are returned:
[object HTMLParagraphElement]
This way it won't throw an error, but it probably won't do what you want. It would probably be wiser to use the object ID as the key and create a unique ID to place the object if the object doesn't already have an ID.
As far as I can tell, any use of using an object as a key can also be done with an id as a key.
source to share
When I run this in Firefox 10:
window.onload = function(){
var doms = {},
item,
element = {
tag: 'input',
name: 'email',
value: null,
dom: null
};
for (var i = 0; i < 10; i++) {
item = document.createElement(element.tag);
item.name = element.name + i;
document.body.appendChild(item);
doms[item] = element;
}
console.log(doms);
};
In the Firebug console, I see the following:
Object { [object HTMLInputElement]={...}}
Expands to:
[object HTMLInputElement] Object { tag="input", name="email", value=null, more...}
dom null
name "email"
tag "input"
value null
Please note that there is only one reference / object pair, not ten. I suspect that you cannot do this, and I would advise against it anyway (instead of a specific quote supporting my guess).
source to share