Why custom elements not support attributes as an object?

安稳与你 提交于 2019-12-01 14:47:22

Try by converting object to JSON string,

var object = { key1: 111, key2: 222};
JSON.stringify(object);

Then when you want to get the value, parse it back to object

JSON.parse(this.getAttribute('data'));

Custom Elements does not modify the standard HTML element attribute behaviour which is always of type string.

Because of that, you shoud instead either:

  1. Send a change Event from your custom element that will trigger the onchange handler.

  2. Register you object/function callback via a custom element method.

  3. Modify a state attribute that will be observed (with Mutation Observer) by its container.

If you want to use attribute anyways you can always use eval().


Example with solution 1 with call to changeHandler():

//define custom element
class DropDown extends HTMLElement 
{
  connectedCallback ()
  {
    var span = this.querySelector( 'span' )

    //define ul list
    var ul = this.querySelector( 'ul' )

    ul.onclick = ev => {
      if ( this.value != ev.target.textContent )
      {
        this.value = ev.target.textContent
        this.setAttribute( 'value', this.value )
        span.textContent = this.value 
        this.dispatchEvent( new CustomEvent( 'change' ) )
      }
    }

    //show or hide
    this.onclick = ev => ul.classList.toggle( 'show' )
    
  }

}
customElements.define( 'drop-down', DropDown )
drop-down  {
  position: relative ;
  cursor: pointer ;
  display: inline-block ;
}
drop-down > span {
  border: 1px solid #aae ;
  padding: 2px 5px ;
}
drop-down > ul {
  position: absolute ;
  top: 4px ; left: 5px ;
  list-style: none ;
  outline: 1px solid #aae ;
  padding: 0 ;
  display: inline-block ;
  opacity: 0 ;
  transition: all 0.3s ease-out ;
  background: white ;
  visibility: hidden ;
  z-index: 10 ;
}
drop-down > ul.show {
  opacity: 1 ;
  visibility: visible ;
}
drop-down > ul > li {
  padding: 2px 5px ;
}
drop-down > ul > li:hover {
  background: lightgoldenrodyellow ;
}
<drop-down onchange="changeHandler()">
  <span>select value</span>
  <ul>
    <li>Chrome</li>
    <li>Firefox</li>
    <li>Opera</li>
    <li>Safari</li>
  </ul>
</drop-down>

<script>
  function changeHandler ()
  {
    console.log( 'changeHandler()', event.target.value )
  }
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!