javascript - Setting web-component properties at the time of it's creation -


i'm creating little spa framework, , decided integrate webcomponents. works fine, i'm curious 1 thing.

i extended html element , html element fragment method add (note might not perfect, it's still under development)

documentfragment.prototype.add = function(options){   let element = document.createelement(options.elementtype);   if (options.innerhtml){     element.innerhtml = options.innerhtml;   }   if (options.id){     element.id = options.id;   }   if (options.attributes){     (let attr in options.attributes){       element.setattribute(attr, options.attributes[attr]);     }   }   if (options.insertbefore){     this.insertbefore(element, options.insertbefore);     return element;   }   this.appendchild(element);   return element; } element.prototype.add = documentfragment.prototype.add; 

now, in view, want use method this:

root.add({   elementtype: "test-component",   attributes: {     attr1: "value",     attr2: "26.1.2016",     attr3: "value"   } 

it works, problem is, createdcallback gets fired before set attributes component, , can't access these attribute in createdcallback.

now, i'm using attributechangedcallback solve this, isn't best solution

attributechangedcallback(attrname, oldval, newval) {       if (attrname == "attr1"){         *do something*       }       if (attrname == "attr2"){         *do something*       } ...     } 

is there better way solve this? avoiding "add" method extending innerhtml of parent element like

<test-component attr1="value"></test-component> 

isn't helpful, since little "add" method simplifies work lot.

every answer appretiated. thanks

createdcallback gets fired whenever element gets created(obvious). useful when using custom elements 'declaratively', i.e. not appending in dom using js.

for use case, createdcallback getting fired execute document.createelement , since executing setattribute post won't accessible in createdcallback method.

using attributechangedcallback valid alternative here. if want consider one, can use attachedcallback gets executed whenever appending node dom i.e executing appendchild on it. take @ article if haven't already.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -