Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active May 14, 2017 11:14
Show Gist options
  • Save WebReflection/113b136c3a0e49b2ac96c6d9f55615e6 to your computer and use it in GitHub Desktop.
Save WebReflection/113b136c3a0e49b2ac96c6d9f55615e6 to your computer and use it in GitHub Desktop.
"use strict";
class Foo {
constructor(root) {
this.render = hyperHTML.bind(root);
this.state = Introspected({}, $ctrl => this.update($ctrl));
this.state.items = [
{ id: 1, text: "foo" },
{ id: 2, text: "bar" },
{ id: 3, text: "baz" }
];
}
update($ctrl) {
this.render`
<ul>${$ctrl.items.map(item => hyperHTML.wire(item)`
<li> ${item.id} / ${item.text} </li>
`)}</ul>
`;
}
}
const foo = new Foo(document.body);
setTimeout(() => {
foo.state.items.push({ id: 4, text: "minions" });
}, 3000);
@WebReflection
Copy link
Author

I have updated hyperHTML with a nice feature such multi wire per same object and by IDs.

You can see a live example of your use-case in this page.

I have also added the ability to set object with handleEvent methods as events to simplify, and reuse, as many callbacks per component as possible.

  class Foo {
  
    constructor(root) {

      this.render = hyperHTML.bind(root);

      this.state = Introspected(
        {
          items: [
            { id: 1, text: 'foo' },
            { id: 2, text: 'bar' },
            { id: 3, text: 'baz' }
          ]
        },
        state => this.update(state)
      );

      // any change to the introspected state will update
      this.state.selectedItem = this.state.items[0];
    }

    // any object with an handleEvent method can be used for any event
    // like it is already for DOM Level 3 via addEventListener
    handleEvent(e) {
      switch (e.type) {
        case 'change':
          this.state.selectedItem = this.state.items.find(
            item => +e.target.value === item.id
          );
          break;
      }
    }

    update(state) {
      this.render`
        <select onchange="${this}">${
          state.items.map(item => hyperHTML.wire(item, ':option')`
          <option value="${item.id}">
            ${item.text}
          </option>
        `)}</select>

        <p>Selected: ${state.selectedItem.text}</p>

        <ul>${state.items.map(item => hyperHTML.wire(item, ':li')`
            <li> ${item.id} / ${item.text} </li>
        `)}</ul>
      `;
    }

  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment