Show HN: Mador – 用 80 行微型 Proxy 状态元组实现任何 DOM 的响应式编程
Show HN: Mador – Make any DOM reactive with a tiny 80-line Proxy state tuple

原始链接: https://github.com/marsbos/mador

Mador 是一个超轻量级(小于 1KB)的响应式 DOM 运行时,专为那些需要在无需完整框架负担的情况下实现响应式功能的开发者而设计。Mador 摒弃了虚拟 DOM、组件化和自定义模板,直接使用现有的 HTML 和 JavaScript 进行开发。 该库通过简单的绑定模式运行: * **`r` (Read/读取):** 通过 CSS 选择器定位 DOM 元素,并将其与特定的状态数据关联。Mador 会自动追踪依赖,仅在相关数值发生变化时更新 DOM。 * **`w` (Write/写入):** 更新应用程序状态。写入操作会自动进行批处理,以确保性能效率。 Mador 以原生 ES 模块形式分发,无需构建步骤或全局依赖。它非常适合为静态页面添加精细的响应式功能,而无需引入大而全的框架。通过将响应式直接绑定到 DOM,Mador 消除了对复杂生命周期管理的需求——当对应的元素从页面中移除时,绑定会自动清理。这是一个极简主义的、基于 MIT 协议的工具,适合推崇原生 Web 标准的开发者。

```Hacker News最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交登录Show HN: Mador – 用一个 80 行的微型 Proxy 状态元组让任何 DOM 具有响应式 (github.com/marsbos)9 分 由 bosmarcel 17 分钟前发布 | 隐藏 | 过往 | 收藏 | 2 条评论 帮助 DylanMerigaud 13 分钟前 | 下一条 [–] 发布得很简洁,祝好运!回复bosmarcel 13 分钟前 | 父级 | 下一条 [–] 非常感谢!回复 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索: ```
相关文章

原文

Make DOM Reactive. Nothing more.

Mador:

  • is a very small reactive DOM runtime.
  • is for people who don't need or want a framework.

It gives you reactive state and a way to bind that state to existing DOM.

Mador is a native ES module and can be used through npm or directly from a 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.

A binding consists of three things:

r(selector, update, read);

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.

State is changed through 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.

When the matching elements are gone, Mador can remove the corresponding reactive runner.

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.

Mador is made to do that.

Mador is intentionally small.

The runtime is currently around 855 bytes minified.

Mador is distributed as an ES module.

import mador from "mador";

No global runtime and no build step is required.

MIT

联系我们 contact @ memedata.com