Last active
May 14, 2017 11:14
-
-
Save WebReflection/113b136c3a0e49b2ac96c6d9f55615e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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); |
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
issue is here:
You should use a wire there to have a fully correct behavior/expectation, but in that demo you cannot use a wire twice because objects are mapped only once per template.
This means you need a helper to map a single item to multiple different wires, like I've done in here:
https://plnkr.co/edit/ozBlLEeqD4MekU4FaTya?p=preview
This also gave me a hint on how to improve, enhance hyperHTML: thank you!