snabbdom源码笔记

162 阅读2分钟

1、snabbdom

用js 模拟vdom vnode结构(用JS对象模拟DOM树) github.com/creeperyang…

snabbdom 主要的接口有:

h(type, data, children),返回 Virtual DOM 树。 patch(oldVnode, newVnode),比较新旧 Virtual DOM 树并更新。

var vnode = h('ul#list',{},[{
    h('li.item',{},'Item 1'),
    h('li.item',{},'Item 2'),
}])

2、h函数---创建vdom,Virtual DOM 树

vnode 模拟真实的dom节点

2、patch函数---打补丁,比对新旧vdom,然后在此同时对真正的DOM做操作,比较新旧 Virtual DOM 树并更新。

patch(container,vnode) patch(container,newVnode)

4、snabbdom大致的思路是?

官方示例:

var snabbdom = require('snabbdom');
/*
init后获得一个patch函数,用于对比新旧vdom树、并更新dom
此处传入的数组,是一组snabbdom模块。
snabbdom模块中包含许多生命周期钩子,用于在snabbdom运行期间做一些额外的处理
比如,解析class、style表达式,修改props,绑定事件等。
snabbdom本身只负责管理vdom和dom的结构,比如新增删除节点、修改文字之类的。
其他操作基本上是由模块完成的。
*/
var patch = snabbdom.init([ // Init patch function with chosen modules
  require('snabbdom/modules/class').default, // makes it easy to toggle classes
  require('snabbdom/modules/props').default, // for setting properties on DOM elements
  require('snabbdom/modules/style').default, // handles styling on elements with support for animations
  require('snabbdom/modules/eventlisteners').default, // attaches event listeners
]);

// 用于创建虚拟DOM(vnode对象)的函数。类似于React.createElement
var h = require('snabbdom/h').default; // helper function for creating vnodes

var container = document.getElementById('container');

var vnode = h('div#container.two.classes', {on: {click: someFn}}, [
  h('span', {style: {fontWeight: 'bold'}}, 'This is bold'),
  ' and this is just normal text',
  h('a', {props: {href: '/foo'}}, 'I\'ll take you places!')
]);
// Patch into empty DOM element – this modifies the DOM as a side effect
/* 
这个操作snabbdom称之为“patch”,也就是打补丁。
实际上就是比对新旧vdom,然后在此同时对真正的DOM做操作。
第一次调用时,传入一个空的HTMLElement作为oldVnode即可。
*/
patch(container, vnode);

var newVnode = h('div#container.two.classes', {on: {click: anotherEventHandler}}, [
  h('span', {style: {fontWeight: 'normal', fontStyle: 'italic'}}, 'This is now italic type'),
  ' and this is still just normal text',
  h('a', {props: {href: '/bar'}}, 'I\'ll take you places!')
]);
// Second `patch` invocation
// 第二次调用时,先前的vnode已经patch过,和真正的HTMLElement连接在一起了。
patch(vnode, newVnode); // Snabbdom efficiently updates the old view to the new state