javascript - How can I add a custom attribute to an HTMLElement, that will default to an empty object on each new instance of the element? -
if add new property prototype of htmlelement, , have default value '{}' (an empty object):
object.defineproperty(htmlelement.prototype, 'customobject', { configurable: true, enumerable: true, writeable: true, value: {} }); now create new div (which htmlelement):
var e = document.createelement('div'); i assign property customobject of e:
e.customobject.prop = "bla"; if alert it, see desired value:
alert(e.customobject.prop); // displays 'bla'. now create new, different div element:
var d = document.createelement('div'); this d should have empty customobject property, right?
however, if alert it:
alert (d.customobject.prop); i unexpected result:
bla how come? when create new element shouldn't have "blank" instance of htmlelement.prototype?
( jsfiddle: http://jsfiddle.net/5pgr38mb/ )
edit: looking solution will work deep cloning (clonenode(true)). meaning - if custom object has properties on element or of children element or child retain value in cloned instance (this normal behavior "native" htmlelement attributes).
i might use prototype getter creates new object property on instance when called:
object.defineproperty(htmlelement.prototype, 'customobject', { enumerable: true, get: function() { if(this.__thiscustomobject === undefined) { this.__thiscustomobject = {}; // or non-enumerable with: // object.defineproperty(this, '__thiscustomobject', { // enumerable: false, // value: {} // }; } return this.__thiscustomobject; }, set: function(val) { this.__thiscustomobject = val; } }); this way, time ask customobject on object first time, creates new object , stores in object's __thiscustomobject property. then, future requests customobject use element's __thiscustomobject property.
note getter-setter pattern close how actual per-element dom properties implemented in web idl specification. difference here per-element value stored in property, rather hidden mapping.
Comments
Post a Comment