Can I use virtual tree directly in my program?
tiye opened this issue ยท 7 comments
Hi @jiyinyiyong can you explain a little more what you're trying to do?
I was from React and it was quite fluent to assemble a virtual DOM, while to get HTML string we need one more function like stringify
. I suppose that diffhtml
still need to parse my HTML string into a virtual DOM in order to generate patches, so if I pass in a virtual DOM will it be faster?
Yes it will be. In fact I'm working on a babel transform right now to make it precompile them as well.
If you wanted to manually ingest a dynamic tree you can use the following functions to generate them:
const createElement = (tagName, attributes, childNodes) => ({
uuid: String(Math.floor(Math.random() * Date.now())),
nodeName: tagName.toLowerCase(),
nodeType: 1,
nodeValue: '',
attributes: Object.keys(attributes || []).map(
keyName => ({
name: keyName,
value: attributes[keyName]
})
),
childNodes: childNodes || [],
})
const createTextElement = value => ({
uuid: String(Math.floor(Math.random() * Date.now())),
nodeName: '#text',
nodeType: 3,
nodeValue: value,
key: '',
attributes: [],
childNodes: [],
})
Here's an example of usage:
createElement('div', { class: 'cool-class' }, [
createElement('p', { onclick(ev) {} }, [
createTextElement('click me')
])
])
To use with diffHTML you'd then pass that value like so:
<div id="parent"></div>
const innerHTML = diff.innerHTML
const element = document.querySelector('#parent')
innerHTML(element, createElement('div', { class: 'cool-class' }, [
createElement('p', { onclick(ev) {} }, [
createTextElement('click me')
])
]))
@jiyinyiyong Here is an example JSFiddle as well: https://jsfiddle.net/tbranyen/xhbnvna3/1/
Hope all this helps!
There's even a onclick
function, that's cool. Thanks.