Reputation: 20245
in linking javascript objects with 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?
Upvotes: 3
Views: 167
Reputation: 49238
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);
};
I see the following in Firebug's console:
Object { [object HTMLInputElement]={...}}
Which expands to:
[object HTMLInputElement] Object { tag="input", name="email", value=null, more...}
dom null
name "email"
tag "input"
value null
Note, there's only one reference/object pair, not ten. I suspect you can't do this, and I would advise against it anyways (in lieu of a specific citation supporting my hunch).
Upvotes: 1
Reputation: 708056
Object keys are strings. So, when you try to use a DOM object as an object key, it will call toString()
on the DOM object and use that as the key. toString()
on DOM objects returns non-unique things like this:
[object HTMLParagraphElement]
So, it won't cause an error, but it probably won't do what you want. It would probably make more sense to use the object's ID as the key and generate a unique ID to put on the object if the object doesn't already have an id.
As best I can tell, any use of using an object as a key can also be done with the id as a key.
Upvotes: 1