Skip to content

Instantly share code, notes, and snippets.

@tavisrudd
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tavisrudd/d2a2e750e105641ed867 to your computer and use it in GitHub Desktop.
Save tavisrudd/d2a2e750e105641ed867 to your computer and use it in GitHub Desktop.
vdom messing with widgets
var diff = require("virtual-dom").diff
var patch = require("virtual-dom").patch
var h = require("virtual-dom").h
//var _ = require("lodash");
var createElement = require("virtual-dom").create
var OddCounterWidget = function(prefix) {this.prefix = prefix;};
OddCounterWidget.prototype.type = "Widget"
OddCounterWidget.prototype.count = 1
OddCounterWidget.prototype.init = function() {
// With widgets, you can use any method you would like to generate the DOM Elements.
// We could get the same result using:
// return createElement(h("div", "Count is: " + this.count))
console.log('init', this.prefix, this.count);
var divElem = document.createElement("div")
var textElem = document.createTextNode("Count is: " + this.count)
divElem.appendChild(textElem)
return divElem
}
OddCounterWidget.prototype.update = function(previous, domNode) {
this.count = previous.count + 1
console.log('update', this.prefix, this.count);
// Only re-render if the current count is odd
if (this.count %2 ) {
// Returning a new element from widget#update
// will replace the previous node
return this.init()
}
return null
}
OddCounterWidget.prototype.destroy = function(domNode) {
// While you can do any cleanup you would like here,
// we don't really have to do anything in this case.
// Instead, we'll log the current count
console.log('destroy', this.prefix, this.count)
}
var tree1 = [new OddCounterWidget('A0'), new OddCounterWidget('A1'), new OddCounterWidget('A2'), new OddCounterWidget('A3')]
var tree2 = _.shuffle(tree1)
var myCounter = tree1
var currentNode = myCounter
var rootNode = createElement(currentNode)
// A simple function to diff your widgets, and patch the dom
var update = function(nextNode) {
var patches = diff(currentNode, nextNode)
rootNode = patch(rootNode, patches)
currentNode = nextNode
}
var alt = false
document.body.appendChild(rootNode)
setInterval(function(){
var tree;
if (alt) {
//tree = h('div', [(alt ? new OddCounterWidget() : 'no')]);
tree = tree1; //h('div', [new OddCounterWidget('a'), new OddCounterWidget('d')]);
} else {
tree = tree2 //h('div', [new OddCounterWidget('b'), new OddCounterWidget('c')]);
}
update(tree);
alt = !alt;
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment