Last active
September 8, 2015 06:27
-
-
Save jayrbolton/6eb946abe6e18d248bd6 to your computer and use it in GitHub Desktop.
Virtual-dom quick setup wrapper
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
// This is a minimalistic way to easily use virtual-dom and avoid repeating any boilerplate code | |
// It's a simple object wrapper with a small api that you can use to set new data and re-render quickly and easily. | |
// Pass in a parentNode (like document.body), a rootComponent (a function that takes a state and returns a VTree), and an initial state object. | |
function view(parentNode, rootComponent, initialState) { | |
this.state = initialState | |
this.tree = rootComponent(initialState) | |
this.rootNode = createElement(this.tree) | |
parentNode.appendChild(this.rootNode) | |
return this | |
} | |
view.prototype.render = function() { | |
if(this.sync) this.sync(this.state) | |
var newTree = this.rootComponent(this.state) | |
var patches = diff(this.tree, newTree) | |
this.rootNode = patch(this.rootNode, patches) | |
this.tree = newTree | |
return state | |
} | |
/* Usage: | |
// Create a vtree function: | |
function hi(state) { return h('p', state.msg) } | |
// Create a new view object: | |
var myView = new view(document.body, hi, {msg: 'hallo welt!'}) | |
// Make changes to the view's state: | |
myView.state = 'bonjour le monde' | |
// Then re-render | |
myView.render() | |
// Callback on every render that you can use for localStorage, ajax, etc: | |
myView.sync = function(state) { .. do something with state .. } | |
// For something more robust, check out https://github.com/jayrbolton/vvvview | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment