I am trying to pass data attribute in custom element as an object but while receiving inside attachedCallback method getting value "[object object]" in a string form.
So can anyone help me to figure out what is the work around to get the attributes as an object inside custom-element(web component).
code sample
<script>
class myElements extends HTMLElement {
createdCallback() {
this.innerHTML = `<h1>Hello</h1>`;
}
attachedCallback() {
console.log(this.getAttribute('data'));
}
}
document.registerElement('my-element', myElements);
</script>
custom element tag
<script>
var object = { key1: 111, key2: 222, key3: function(){return "hi"}, key4:[1,2,3]};
function changeHandler() {
page('/default', function() {
// some logic to decide which route to redirect to
if (admin) {
page.redirect('/admin');
} else {
page.redirect('/guest');
}
});
}
</script>
<my-element data="object" onchange="changeHandler"></my-element>
Note: suppose that <my-element>
is a dropdown which gives user option to choose some value.
Solution: Still no native solution in custom-element specs(v0 and v1).
Since Custom Elements doesn't support data binding so we need a sugaring layer for that (e.g., Polymer or SkateJS) as mention by @tony in the comment.
Try by converting object to JSON string,
Then when you want to get the value, parse it back to object