WebReflection / hyperHTML

A Fast & Light Virtual DOM Alternative
ISC License
3.06k stars 112 forks source link

emit event on data attribute change #372

Closed KiranMantha closed 5 years ago

KiranMantha commented 5 years ago

with the data attributes, we can pass an object to children but there is no way to listen to changes in that data object. is there any way to do that?

customElements.define(
  'h-welcome',
  class HyperWelcome extends HTMLElement {
    get html() { return this._html || (this._html = hyperHTML.bind(this)); }

    get user() { return this._user; }
    set user(value) {
      this._user = value;
      this.render();
    }

    render() { return this.html`<h1>Hello, ${this._user.name}</h1>`; }
  }
);

customElements.define(
  'h-root',
  class HyperWelcome extends HTMLElement {
constructor(){
this.user = {name: 'sara'}
}
    get html() { return this._html || (this._html = hyperHTML.bind(this)); }
updateName(){
this.user.name = 'joe'; // not triggering setter in h-welcome
this.user = {name: 'joe'}; // triggering setter in h-welcome
}
    render() { return this.html`<button onclick=${()=>this.updateName();}>hi</button><h-welcome data=${this.user}></h-welcome>`; }
  }
);

in the above example when I change user.name to 'joe' in h-root, the setter in h-welcome is not getting triggered. if i assign a new object to user in h-root then the setter is getting triggered. it would be better if there is an event like ondataupdated to render h-welcome automatically. Thanks.

WebReflection commented 5 years ago

There is no setter/getter so I'm not sure I understand your concern. You set a property of an object that has nothing to do with the element itself, you need to add the event emitter logic in that object

KiranMantha commented 5 years ago

my issue is, I want to render the view whenever there is a change in the data attribute. is there any way to do that?

WebReflection commented 5 years ago

There are many ways, but none of these are relevant for this library.

Use a data setter and dispatch the event, or observe data attribute and dispatch on attributeChangedCallback. All I'm saying is that you are looking for a solution with custom elements, not with hyperHTML.

Maybe the solution is here already? https://gist.github.com/WebReflection/ec9f6687842aa385477c4afca625bbf4