mowatermelon / learn-es6

一个有趣的人写的有趣的前端基础
http://blog.iiwhy.cn/learn-es6
7 stars 5 forks source link

learn Snbbdom #94

Open mowatermelon opened 4 years ago

mowatermelon commented 4 years ago

介绍

官方地址

https://github.com/snabbdom/snabbdom

官方说明

Snabbdom: A virtual DOM library with focus on simplicity, modularity, powerful features and performance.

一个虚拟DOM库,重点放在简单性,模块化,强大的功能和性能上。

Virtual DOM is awesome. It allows us to express our application's view as a function of its state. But existing solutions were way way too bloated, too slow, lacked features, had an API biased towards OOP and/or lacked features I needed.

Snabbdom consists of an extremely simple, performant and extensible core that is only ≈ 200 SLOC. It offers a modular architecture with rich functionality for extensions through custom modules. To keep the core simple, all non-essential functionality is delegated to modules.

You can mold Snabbdom into whatever you desire! Pick, choose and customize the functionality you want. Alternatively you can just use the default extensions and get a virtual DOM library with high performance, small size and all the features listed below.

虚拟DOM非常棒。它允许我们将应用程序的视图表达为其状态的函数。但现有的解决方案过于臃肿、速度太慢、缺乏特性、API偏向于OOP和/或缺少我需要的特性。

Snabbdom由一个非常简单、性能好、可扩展的内核组成,它的内核只有大约200个SLOC。它提供了一个模块化的体系结构,具有丰富的功能,可以通过自定义模块进行扩展。为了保持核心的简单性,所有不必要的功能都委托给了模块。

你可以把圈套塑造成你想要的任何东西!选择、选择和自定义所需的功能。或者,您可以使用默认扩展名,获得一个具有高性能、小尺寸和下面列出的所有功能的虚拟DOM库。


案例

基础渲染和修改案例

var snabbdom = require('snabbdom');
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
]);
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
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

更多案例


核心方法

snabbdom.init

The core exposes only one single function snabbdom.init. This init takes a list of modules and returns a patch function that uses the specified set of modules.

核心仅公开一个功能snabbdom.init。这init将获取模块列表,并返回patch使用指定模块集的函数。

var patch = snabbdom.init([
  require('snabbdom/modules/class').default,
  require('snabbdom/modules/style').default,
]);

patch

The patch function returned by init takes two arguments. The first is a DOM element or a vnode representing the current view. The second is a vnode representing the new, updated view.

patch返回的函数init带有两个参数。第一个是表示当前视图的DOM元素或vnode。第二个是代表新的更新视图的vnode。

If a DOM element with a parent is passed, newVnode will be turned into a DOM node, and the passed element will be replaced by the created DOM node. If an old vnode is passed, Snabbdom will efficiently modify it to match the description in the new vnode.

如果传递带有父项的DOM元素,newVnode它将被转换为DOM节点,并且所传递的元素将被创建的DOM节点替换。如果通过了旧的vnode,Snabbdom将有效地对其进行修改以匹配新vnode中的描述。

Any old vnode passed must be the resulting vnode from a previous call to patch. This is necessary since Snabbdom stores information in the vnode. This makes it possible to implement a simpler and more performant architecture. This also avoids the creation of a new old vnode tree.

传递的任何旧vnode必须是先前调用产生的vnode patch。这是必需的,因为Snabbdom将信息存储在vnode中。这使得实现更简单,更高性能的体系结构成为可能。这也避免了创建新的旧vnode树。

patch(oldVnode, newVnode);

Unmounting

While there is no API specifically for removing a VNode tree from its mount point element, one way of almost achieving this is providing a comment VNode as the second argument to patch, such as:

虽然没有专门用于从其挂载点元素中删除VNode树的API,但几乎可以实现这一目的的一种方法是提供注释VNode作为的第二个参数patch,例如:

patch(oldVnode, h('!', { hooks: { post: () => { /* patch complete */ } } }))

snabbdom/h

It is recommended that you use snabbdom/h to create vnodes. h accepts a tag/selector as a string, an optional data object and an optional string or array of children.

建议您用于snabbdom/h创建vnode。h接受标记/选择器作为字符串,可选数据对象和可选字符串或子级数组。

var h = require('snabbdom/h').default;
var vnode = h('div', {style: {color: '#000'}}, [
  h('h1', 'Headline'),
  h('p', 'A paragraph'),
]);

snabbdom/tovnode

Converts a DOM node into a virtual node. Especially good for patching over an pre-existing, server-side generated content.

将DOM节点转换为虚拟节点。特别适合修补现有的服务器端生成的内容。

var snabbdom = require('snabbdom')
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
]);
var h = require('snabbdom/h').default; // helper function for creating vnodes
var toVNode = require('snabbdom/tovnode').default;

var newVNode = h('div', {style: {color: '#000'}}, [
  h('h1', 'Headline'),
  h('p', 'A paragraph'),
]);

patch(toVNode(document.querySelector('.container')), newVNode)

Hooks

Hooks are a way to hook into the lifecycle of DOM nodes. Snabbdom offers a rich selection of hooks. Hooks are used both by modules to extend Snabbdom, and in normal code for executing arbitrary code at desired points in the life of a virtual node.

挂钩是挂钩DOM节点生命周期的一种方法。Snabbdom提供了丰富的钩子选择。模块使用钩子来扩展Snabbdom,并在常规代码中使用钩子在虚拟节点生命周期中的期望点执行任意代码。

Overview

Name Triggered when Arguments to callback
pre the patch process begins none
init a vnode has been added vnode
create a DOM element has been created based on a vnode emptyVnode, vnode
insert an element has been inserted into the DOM vnode
prepatch an element is about to be patched oldVnode, vnode
update an element is being updated oldVnode, vnode
postpatch an element has been patched oldVnode, vnode
destroy an element is directly or indirectly being removed vnode
remove an element is directly being removed from the DOM vnode, removeCallback
post the patch process is done none

The following hooks are available for modules: pre, create, update, destroy, remove, post.

下面的挂钩可用于Module:pre,create, update,destroy,remove,post。

The following hooks are available in the hook property of individual elements: init, create, insert, prepatch, update, postpatch, destroy, remove.

下面钩在可用hook单个元件的属性:init,create,insert,prepatch,update, postpatch,destroy,remove。

为什么 pre 和 post 不能使用呢?因为这两个钩子不在 vnode 的生命周期之中,在 vnode 创建之前,pre 已经执行完毕,在 vnode 卸载完毕之后,post 钩子才开始执行。


Usage

To use hooks, pass them as an object to hook field of the data object argument.

要使用钩子,请将它们作为对象传递给hook数据对象参数的字段。

h('div.row', {
  key: movie.rank,
  hook: {
    insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight; }
  }
});

Module 模块

Module 是 snabbdom 的一个核心概念,snabbdom 的核心主干代码只实现了元素、id、class(不包含动态赋值)、元素内容(包括文本节点在内的子节点)这四个方面;而其他诸如 style 样式、class 动态赋值、attr 属性等功能都是通过 Module 扩展的,它们写成了 snabbdom 的内部默认 Module,在需要的时候引用就行了。

Module 的本质是一个对象,对象的键由一些钩子(Hooks)的名称组成,键值都是函数,这些函数能够在特定的 vnode/DOM 生命周期触发,并接受规定的参数,能够对周期中的 vnode/DOM 进行操作。

mowatermelon commented 4 years ago

https://blog.csdn.net/weixin_34072857/article/details/91441072

mowatermelon commented 4 years ago

为什么说虚拟DOM快?

虚拟DOM不会进行排版与重绘操作 虚拟DOM进行频繁修改,然后一次性比较并修改真实DOM中需要改的部分(注意!),最后并在真实DOM中进行排版与重绘,减少过多DOM节点排版与重绘损耗 真实DOM频繁排版与重绘的效率是相当低的 虚拟DOM有效降低大面积(真实DOM节点)的重绘与排版,因为最终与真实DOM比较差异,可以只渲染局部(同2) 使用虚拟DOM的损耗计算: 总损耗=虚拟DOM增删改+(与Diff算法效率有关)真实DOM差异增删改+(较少的节点)排版与重绘 直接使用真实DOM的损耗计算: 总损耗=真实DOM完全增删改+(可能较多的节点)排版与重绘 总之,一切为了减弱频繁的大面积重绘引发的性能问题,不同框架不一定需要虚拟DOM,关键看框架是否频繁会引发大面积的DOM操作。

https://segmentfault.com/a/1190000020733831