Created
May 16, 2014 19:06
-
-
Save maccman/56db8e02c7e51d033a5a to your computer and use it in GitHub Desktop.
Rendering with an Event Loop
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
</head> | |
<body> | |
<script type="text/javascript" src="../lib/parrot.js"></script> | |
<script type="text/javascript" src="../lib/parrot.example.js"></script> | |
<script type="text/javascript"> | |
var widget = new ParrotWidget | |
document.body.appendChild(widget.el); | |
Parrot.append(widget); | |
Parrot.run(); | |
</script> | |
</body> | |
</html> |
This file contains hidden or 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
eql = (val1, val2) -> | |
JSON.stringify(val1) is JSON.stringify(val2) | |
dup = (val) -> | |
JSON.parse(JSON.stringify(val)) | |
class @Parrot | |
@run: => | |
@render() | |
requestAnimationFrame(@run) | |
@render: => | |
for component in @components | |
if component.isDirty() | |
component.render() | |
@append: (component) => | |
@components or= [] | |
@components.push(component) | |
class Parrot.Component | |
tag: 'div' | |
className: 'component' | |
constructor: -> | |
@el = document.createElement(@tag) | |
@el.className += @className | |
@previousState = {} | |
@state = {} | |
isDirty: -> | |
not eql(@state, @previousState) | |
render: -> | |
@previousState = dup(@state) |
This file contains hidden or 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
class @ParrotWidget extends @Parrot.Component | |
constructor: -> | |
super | |
@state.level = 0 | |
setInterval => | |
@state.level += 1 | |
, 400 | |
render: -> | |
super | |
@el.innerHTML = "Level: #{@state.level}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment