Share
Embed
Transcript
94 slides
-
Hola! Soy Karen " Developer en Wingu (@desdewingu) => Trabajando
en Nilus (@nilusorg) @keyserfaty -
// Crea los nodos const $input = document.createElement('input') $input.setAttribute('type', 'text')
$input.setAttribute('value', '') const $textContainer = document.createElement('div') $textContainer.setAttribute('class', 'text-container') const $container = document.createElement('div') $container.setAttribute('class', 'container') $container.appendChild($input) $container.appendChild($textContainer) const $root = document.querySelector('#root') $root.appendChild($container) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
// Appendea eventos al input $input.addEventListener('keyup', function (e) { const
text = e.target.value const $textNode = document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
Sería mejor si pudiéramos hacer todos los cambios en el
DOM en grupo en vez de individualmente -
Digamos que queremos hacer nuestra ““app”” de nuevo pero usando
la API del DOM lo menos posible -
Podemos probar creando una representación de esos nodos y después
crearlos todos juntos al final -
const container = { type: 'div', props: { class: 'container'
}, children: [ // input & text-container ] } -
Como crear estos objetos es una experiencia horrible podemos crear
una función que los cree por nosotros -
const element = ( h('div', { className: 'container' }, h('input',
{ type: 'text', onKeyUp: () => {} }), h('div', { className: 'text-container' }, ‘Un texto!’) ) ) -
const element = ( h('div', { className: 'container' }, h('input',
{ type: 'text', onKeyUp: () => {} }), h('div', { className: 'text-container' }, ‘Un texto!’) ) ) => const element = ( { type: 'div', props: { className: 'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: () => {} } }, { type: 'div', props: { className: 'text-container' }, children: [ ‘Un texto!’ ] } ] } ) -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } return document.createElement(node.type) } -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } const $el = document.createElement(node.type) node.children .map(child => createElement(child)) .forEach(childNode => $el.appendChild(childNode)) return $el } -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } const $el = document.createElement(node.type) node.children .map(child => createElement(child)) .forEach(childNode => $el.appendChild(childNode)) return $el } -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } const $el = document.createElement(node.type) setProps($el, node.props) setEvents($el, node.props) node.children .map(child => createElement(child)) .forEach(childNode => $el.appendChild(childNode)) return $el } -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } const $el = document.createElement(node.type) setProps($el, node.props) setEvents($el, node.props) node.children .map(child => createElement(child)) .forEach(childNode => $el.appendChild(childNode)) return $el } -
const setProp = ($el, name, value) => { if (isEventProp(name))
{ return } else if (name === 'className') { $el.setAttribute('class', value) } else { $el.setAttribute(name, value) } } const setProps = ($el, props) => { Object.keys(props) .forEach(prop => setProp($el, prop, props[prop])) } -
const setEvent = ($el, name, value) => { $el.addEventListener(extractName(name), value)
} const setEvents = ($el, props) => { Object.keys(props) .forEach(prop => isEventProp(prop) ? setEvent($el, prop, props[prop]) : null ) } -
const createElement = node => { if (typeof node ===
'string') { return document.createTextNode(node) } const $el = document.createElement(node.type) setProps($el, node.props) setEvents($el, node.props) node.children .map(child => createElement(child)) .forEach(childNode => $el.appendChild(childNode)) return $el } -
Supongamos que estamos guardando nuestro state de alguna forma (con
Redux, por ejemplo) -
Si queremos que nuestra app cambie cuando hay un cambio
en el state no podemos hacer los cambios en el eventListener -
$input.addEventListener('keyup', function (e) { const text = e.target.value const $textNode
= document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
Por qué mejor no armamos una función a la que
le pasemos nuestro árbol de nodos -
Y que haga los cambios que necesita comparándolo con el
árbol anterior -
$input.addEventListener('keyup', function (e) { const text = e.target.value const $textNode
= document.createTextNode(text) const $oldTextNode = $textContainer.childNodes[0] if (!$oldTextNode) { $textContainer.appendChild($textNode) } else { $textContainer.replaceChild($textNode, $oldTextNode) } }) -
Pero va a ser genérica y va a funcionar para
cualquier cambio que se produzca en el árbol de nodos -
Momento 0: No tenemos nodos en el DOM Momento 1:
Hacemos el primer rendering de los nodos -
Árbol 1: Árbol 2: (nada) { type: 'div', props: {
className: 'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: updateText } }, { type: 'div', props: { className: 'text-container' }, children: [] } ] } -
const updateElement = ($parent, newNode, oldNode) => { if (!oldNode)
{ $parent.appendChild(createElement(newNode)) } } -
const updateElement = ($parent, newNode, oldNode) => { if (!oldNode)
{ $parent.appendChild(createElement(newNode)) } } -
Momento 0: el div está vacío Momento 1: el div
tiene un textElement adentro con el texto ‘TEXTO!’ -
Árbol 1: Árbol 2: { type: 'div', props: { className:
'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: updateText } }, { type: 'div', props: { className: 'text-container' }, children: [‘TEXTO!’] } ] } { type: 'div', props: { className: 'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: updateText } }, { type: 'div', props: { className: 'text-container' }, children: [] } ] } -
CASO 2: El contenido de uno de los children cambió
y hay que actualizarlo -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } } -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } } -
Árbol 1: Árbol 2: { type: 'div', props: { className:
'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: updateText } }, { type: 'div', props: { className: 'text-container' }, children: [‘TEXTO!’] } ] } { type: 'div', props: { className: 'container' }, children: [ { type: 'input', props: { type: 'text', onKeyUp: updateText } }, { type: 'div', props: { className: 'text-container' }, children: [] } ] } -
CASO 3: Uno de los children tenía un nodo que
ya no tiene más -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (!newNode) { $parent.removeChild($parent.childNodes[index]) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } } -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (!newNode) { $parent.removeChild($parent.childNodes[index]) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } } -
Esto nos va a servir para un elemento pero necesitamos
que la función recorra todo el árbol -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (!newNode) { $parent.removeChild($parent.childNodes[index]) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } else if (newNode.type) { const newLength = newNode.children.length const oldLength = oldNode.childNodes.length for (let i = 0; i < newLength || i < oldLength; i++) { updateElement($parent.childNodes[index], newNode.children[i], oldNode.children[i], i) } } } -
const updateElement = ($parent, newNode, oldNode, index = 0) =>
{ if (!oldNode) { $parent.appendChild(createElement(newNode)) } else if (!newNode) { $parent.removeChild($parent.childNodes[index]) } else if (nodeChanged(newNode, oldNode)) { $parent.replaceChild(createElement(newNode), $parent.childNodes[index]) } else if (newNode.type) { const newLength = newNode.children.length const oldLength = oldNode.childNodes.length for (let i = 0; i < newLength || i < oldLength; i++) { updateElement($parent.childNodes[index], newNode.children[i], oldNode.children[i], i) } } } -
3- Hacer cambios en el árbol de nodos cuando se
produzca algún evento -
Compara dos árboles de nodos (del virtual DOM) y actualiza
solo las partes que cambiaron -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Crea nodos en el vDOM => Crea los nodos en
el DOM => (Cambios / eventos) => Aplica el diffing algorithm => Hace patching en el DOM -
Entonces: 1- Creamos un virtual DOM (`h`) 2- Creamos los
elementos en el DOM (`createElement`) 3- Aplicamos los cambios necesarios (`updateElement`) -
Muy interesante todo Karen. A dónde puedo ir a leer
más sobre esto?