【文章标题】:Show HN: Mador – Make any DOM reactive with a tiny 80-line Proxy state tuple 【文章标题】:Show HN: Mador —— 用80行Proxy状态元组让任何DOM实现响应式
【文章正文】: Mador:
- is a very small reactive DOM runtime.
- is for people who don’t need or want a framework. Mador:
- 是一个极简的响应式DOM运行时
- 专为不需要/不想使用框架的人群设计
It gives you reactive state and a way to bind that state to existing DOM. 它提供响应式状态及将该状态绑定到现有DOM的方法
Mador is a native ES module and can be used through npm or directly from a CDN. Mador是原生ES模块,可通过npm或直接从CDN使用
import mador from “https://cdn.jsdelivr.net/npm/@marsbos/mador@latest/dist/mador.js”;
const [r, w] = mador({
count: 1,
});
r(
“.counter”,
(el, count) => {
el.textContent = Count: ${count};
},
(state) => state.count,
);
r(
“.another-counter”,
(el, count) => {
el.textContent = count * 3;
},
(state) => state.count,
);
w((state) => {
state.count++;
});
And that’s basically all. 基本用法就是这些
There are no components, templates or virtual DOM. Mador works with the DOM you already have. 没有组件、模板或虚拟DOM。Mador直接操作现有DOM
A binding consists of three things: r(selector, update, read); 绑定包含三个要素: r(选择器, 更新函数, 读取函数);
selector selects the elements to update. 选择器用于选取待更新元素
update receives each element and the value returned by read. 更新函数接收元素和读取函数的返回值
read selects the state the binding depends on. 读取函数选取绑定依赖的状态
r( “.counter”, (el, count) => { el.textContent = count * 2; }, (state) => state.count, );
Mador tracks the properties read by the binding and only reruns it when those dependencies change. Mador会追踪绑定读取的属性,仅在这些依赖变更时重新执行
State is changed through w: 通过w函数修改状态: w((state) => { state.count++; });
Writes are batched, so multiple changes made in the same write are processed together. 写入操作会被批量处理,同次写入的多个变更将合并执行
‘Bindings’ are associated with the DOM they update. 绑定与其更新的DOM相关联
When the matching elements are gone, Mador can remove the corresponding reactive runner. 当匹配元素消失时,Mador会自动移除对应的响应式执行器
There is no component lifecycle to manage. 无需管理组件生命周期
Sometimes a page doesn’t need a framework. 有时页面并不需要框架
It already has HTML & Javascript, but is just needs a little reactivity. 已有HTML和JavaScript,只是需要一点响应式功能
Mador is made to do that. Mador正是为此而生
Mador is intentionally small. Mador刻意保持精简
The runtime is currently around 855 bytes minified. 当前运行时压缩后仅约855字节
Mador is distributed as an ES module. 以ES模块形式分发 import mador from “mador”;
No global runtime and no build step is required. 无需全局运行时,也不需要构建步骤
MIT MIT协议