A thunk optimization for virtual-dom
For an introduction on Thunk interface in general, see virtual-dom doc.
Use Thunk when you want to avoid re-rendering subtrees.
Thunk will only re-evaluate the subtree if the arguments
you pass to it change. This means you should use an immutable
data structure (like observ-struct)
var Thunk = require("vdom-thunk")
function render(state) {
return h('div', [
Thunk(header, state.head),
main(),
Thunk(footer, state.foot)
])
}
function header(head) { ... }
function main() { ... }
function footer(foot) { ... }The above example demonstrates how we can only evaluate the
header() function when state.head changes.
The Thunk will internally cache the previous state.head and
not re-evaluate the expensive header() function unless the
state.head state has changed.
See docs.mli for the jsig type definition
vdom-thunk : (fn: Function<VElem>, ...args: Any) => VThunkThunk takes a fn function that returns a virtual node,
probably created by virtual-hyperscript.
The rest of the arguments passed to Thunk will be passed to
the fn you pass.
Thunk returns a virtual thunk that can be used in vtree/diff
and in vdom/create-element from vtree and
vdom
To make placing a "key" on a Thunk easier, you can set a
"key" or "id" property on the second argument to Thunk.
This allows you to give a list of keyed Thunk's to vtree
which will increase performance by using the key algorithm
in the virtual dom diff to move DOM nodes around instead of
mutating them.
vdom-thunk/partial : (
eq: (Array<Any>, Array<Any>) => Boolean
) => (fn: Function<VElem>, ...args: Any) => VThunkpartial takes a comparison function and returns a Thunk
function as defined above.
You can use partial to create your own Thunk function with
a custom comparison function.
Your comparison function should take two arrays of arguments and
return true if the arrays are the same.
The default implementation of this comparison function is shallow comparison of the arrays and checking that the values at each index are the exact same reference to an object.
vdom-thunk/immutable-thunk : (
fn: (...args: Any) => VElem,
args: Array<Any>,
key: String | null,
eqFn: (Array<Any>, Array<Any>) => Boolean
) => VThunkvdom-thunk will use ImmutableThunk under the hood. The
ImmutableThunk interface is a lower level interface that
you can use directly if you want slightly more performance
or customizability.
It takes a function that will be evaluated to a virtual element
for vtree and a set of args that it will call the function
with.
It also takes a key which it sets on the returned VThunk and
the comparison function used to do arguments comparison.
npm install vdom-thunk
- Raynos