Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass js Object and functions to a web component

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

like image 424
Vikrant Agrawal Avatar asked Apr 02 '19 06:04

Vikrant Agrawal


2 Answers

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
like image 143
Supersharp Avatar answered Sep 28 '22 07:09

Supersharp


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);
like image 26
Intervalia Avatar answered Sep 28 '22 08:09

Intervalia