Created
July 27, 2017 18:00
-
-
Save AdamMaras/9530bb4e4e3e8aac81bafe969f015828 to your computer and use it in GitHub Desktop.
VDOM with generators sample
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
import { render } from "vdom-generator"; | |
function* Clock(props, update) { | |
let clockText = new Date().toTimeString(); | |
const timer = setInterval(() => { | |
clockText = new Date().toTimeString(); | |
update.onAnimationFrame(); | |
}, props.interval); | |
let lastClockText = clockText; | |
while ((props = yield)) { | |
if (clockText !== lastClockText) { | |
yield ( | |
<span> | |
{clockText} | |
</span> | |
); | |
} else { | |
yield null; | |
} | |
} | |
clearInterval(timer); | |
} | |
async function CurrentMessage(props) { | |
const messageResponse = await fetch("/api/message"); | |
const message = await messageResponse.text(); | |
return ( | |
<h1> | |
{message} | |
</h1> | |
); | |
} | |
async function* NumberedMessage(_, update) { | |
const getMessage = async number => { | |
const messageResponse = await fetch("/api/message"); | |
return await messageResponse.text(); | |
}; | |
let messageNumber = 0; | |
const handleUp = () => { | |
messageNumber++; | |
update(); | |
}; | |
const handleDown = () => { | |
if (messageNumber > 0) { | |
messageNumber--; | |
update(); | |
} | |
}; | |
const container = children => | |
<div> | |
{children} | |
<button onClick={handleDown}>Down</button> | |
<button onClick={handleUp}>Up</button> | |
</div>; | |
while (yield) { | |
yield container(<em>Loading...</em>); | |
const message = await getMessage(messageNumber); | |
yield container( | |
<strong> | |
{message} | |
</strong> | |
); | |
} | |
} | |
const App = props => | |
<div> | |
<Clock /> | |
<CurrentMessage /> | |
<NumberedMessage /> | |
</div>; | |
render(App, document.getElementById("app")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment