How to pass js Object and functions to a web component

一曲冷凌霜 提交于 2020-06-28 03:40:38

问题


Hi All I am a beginner in javaScript and currently exploring JS Web-component and I got stuck due to some use cases

1 ) I want to pass a JS Object into my component like

<my-component data=obj ></my-component> 

And require to use inside my component code Like

connectedCallback () {
    console.log(this.data) // it should print {"name":"xyz" , "role" : "dev"}
} 

2 ) I also need to pass some functions or maybe call back functions like.

function myFunction(e){
   console.log(e)
}

<my-component click=myFunction ></my-component>

please try to add code snippet also in ans that will help me to learn more JS. Thanks


回答1:


You should pass large object by Javascript.

Via a custom element method:

let comp = document.querySelector( 'my-component' )
comp.myMethod( obj )

Or setting a property:

comp.data = obj



回答2:


It is best to pass in complex data using a property and not an attribute.

myEl.data = {a:1,b:'two'};

The standard on events work fine on a custom element:

function myFunction(e){
  alert(JSON.stringify(e.target.data));
  e.target.data = {a:1,b:"two"};
}

class MyComponent extends HTMLElement {
  constructor() {
    super();
    this._data = 0;
    this.attachShadow({mode:'open'}).innerHTML="Click Me";
  }

  static get observedAttributes() {
    return ['data'];
  }

  attributeChangedCallback(attrName, oldVal, newVal) {
    if (oldVal !== newVal) {

    }
  }

  get data() {
    return this._data;
  }
  set data(newVal) {
    this._data = newVal;
  }
}

customElements.define('my-component', MyComponent);
<my-component onclick="myFunction(event)"></my-component>

If your component dispatches a custom event then it is best to access it through code:

function specialEventHandler(evt) {
  // do something
}

myEl.addEventListener('special-event;', specialEventHandler);



回答3:


Ad 1) You need to use JSON.stringify(obj) Ad 2) As far as I know All attributes need to be defined as strings. You can pass the function that is global and inside component try to eval(fn)




回答4:


I did a Udemy course with Andreas Galster and the tutor passed in a JSON object via attribute.

As you can see it needs encodeURIComponent and decodeURIComponent as well to

attributeChangedCallback (name, oldValue, newValue) {
        if (newValue && name === 'profile-data') {
            this.profileData = JSON.parse(decodeURIComponent(newValue));
            this.removeAttribute('profile-data');
        }

        this.render();
    }

Pass in:

<profile-card profile-data=${encodeURIComponent(JSON.stringify(profile))}>

</profile-card>

Hope this helps. The code worked fine for me.



来源:https://stackoverflow.com/questions/55468533/how-to-pass-js-object-and-functions-to-a-web-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!