响应性本质上是关于系统如何对数据变化作出反应,有不同类型的响应性。然而,在这篇文章中,我们关注的是响应性,即响应数据变化而采取行动。
作为一名前端开发者,Pavel Pogosov 每天都要面对这个问题。因为浏览器本身是一个完全异步的环境。现代 Web 界面必须快速响应用户的操作,这包括更新 UI、发送网络请求、管理导航和执行各种其他任务。
尽管人们常常将响应性与框架联系在一起,Pavel Pogosov 认为通过纯 JavaScript 实现响应性可以学到很多。所以,我们将自己编写一些模式代码,并研究一些基于响应性的原生浏览器 API。
PubSub(发布-订阅模式)
自定义事件作为浏览器版本的 PubSub
自定义事件目标
观察者模式
使用 Proxy 的响应式属性
单个对象属性和响应性
使用 MutationObserver 的响应式 HTML 属性
使用 IntersectionObserver 的响应式滚动
- class PubSub {
- constructor() {
- this.subscribers = {};
- }
-
- subscribe(event, callback) {
- if (!this.subscribers[event]) {
- this.subscribers[event] = [];
- }
-
- this.subscribers[event].push(callback);
- }
-
- // 向特定事件的所有订阅者发布消息
- publish(event, data) {
- if (this.subscribers[event]) {
- this.subscribers[event].forEach((callback) => {
- callback(data);
- });
- }
- }
- }
-
- const pubsub = new PubSub();
-
- pubsub.subscribe('news', (message) => {
- console.log(`订阅者1收到了新闻:${message}`);
- });
-
- pubsub.subscribe('news', (message) => {
- console.log(`订阅者2收到了新闻:${message}`);
- });
-
- // 向 'news' 事件发布消息
- pubsub.publish('news', '最新头条新闻:...');
-
- // 控制台日志输出:
- // 订阅者1收到了新闻:最新头条新闻:...
- // 订阅者2收到了新闻:最新头条新闻:...
一个常见的使用示例是 Redux。这款流行的状态管理库基于这种模式(或更具体地说,是 Flux 架构)。在 Redux 的上下文中,工作机制相当简单:
发布者:store 充当发布者。当一个 action 被派发时,store 会通知所有订阅的组件状态的变化。 订阅者:应用程序中的 UI 组件是订阅者。它们订阅 Redux store 并在状态变化时接收更新。
浏览器通过 CustomEvent 类和 dispatchEvent 方法提供了一个用于触发和订阅自定义事件的 API。后者不仅能让我们触发事件,还能附加任何想要的数据。
- const customEvent = new CustomEvent('customEvent', {
- detail: '自定义事件数据', // 将所需数据附加到事件
- });
-
- const element = document.getElementById('.element-to-trigger-events');
-
- element.addEventListener('customEvent', (event) => {
- console.log(`订阅者1收到了自定义事件:${event.detail}`);
- });
-
- element.addEventListener('customEvent', (event) => {
- console.log(`订阅者2收到了自定义事件:${event.detail}`);
- });
-
- // 触发自定义事件
- element.dispatchEvent(customEvent);
-
- // 控制台日志输出:
- // 订阅者1收到了自定义事件:自定义事件数据
- // 订阅者2收到了自定义事件:自定义事件数据
如果你不想在全局 window 对象上分派事件,可以创建你自己的事件目标。
通过扩展原生 EventTarget 类,你可以向其新实例分派事件。这确保你的事件仅在新类本身上触发,避免了全局传播。此外,你可以直接将处理程序附加到这个特定实例上。
- class CustomEventTarget extends EventTarget {
- constructor() {
- super();
- }
-
- // 触发自定义事件的自定义方法
- triggerCustomEvent(eventName, eventData) {
- const event = new CustomEvent(eventName, { detail: eventData });
- this.dispatchEvent(event);
- }
- }
-
- const customTarget = new CustomEventTarget();
-
- // 向自定义事件目标添加事件监听器
- customTarget.addEventListener('customEvent', (event) => {
- console.log(`自定义事件收到了数据:${event.detail}`);
- });
-
- // 触发自定义事件
- customTarget.triggerCustomEvent('customEvent', '你好,自定义事件!');
-
- // 控制台日志输出:
- // 自定义事件收到了数据:你好,自定义事件!
观察者模式与 PubSub 非常相似。你订阅 Subject,然后它通知其订阅者(观察者)关于变化,使他们能够做出相应的反应。这种模式在构建解耦和灵活的架构中发挥了重要作用。
- class Subject {
- constructor() {
- this.observers = [];
- }
-
- addObserver(observer) {
- this.observers.push(observer);
- }
-
- // 从列表中移除观察者
- removeObserver(observer) {
- const index = this.observers.indexOf(observer);
-
- if (index !== -1) {
- this.observers.splice(index, 1);
- }
- }
-
- // 通知所有观察者关于变化
- notify() {
- this.observers.forEach((observer) => {
- observer.update();
- });
- }
- }
-
- class Observer {
- constructor(name) {
- this.name = name;
- }
-
- // 通知时调用的更新方法
- update() {
- console.log(`${this.name} 收到了更新。`);
- }
- }
-
- const subject = new Subject();
- const observer1 = new Observer('观察者1');
- const observer2 = new Observer('观察者2');
-
- // 将观察者添加到主体
- subject.addObserver(observer1);
- subject.addObserver(observer2);
-
- // 通知观察者关于变化
- subject.notify();
-
- // 控制台日志输出:
- // 观察者1 收到了更新。
- // 观察者2 收到了更新。
如果你想对对象的变化做出反应,Proxy 是一个好方法。它让我们在设置或获取对象字段的值时实现响应性。
- const person = {
- name: 'Pavel',
- age: 22,
- };
-
- const reactivePerson = new Proxy(person, {
- // 拦截设置操作
- set(target, key, value) {
- console.log(`将 ${key} 设置为 ${value}`);
- target[key] = value;
-
- // 表示设置值是否成功
- return true;
- },
- // 拦截获取操作
- get(target, key) {
- console.log(`获取 ${key}`);
-
- return target[key];
- },
- });
-
- reactivePerson.name = 'Sergei'; // 将 name 设置为 Sergei
- console.log(reactivePerson.name); // 获取 name: Sergei
-
- reactivePerson.age = 23; // 将 age 设置为 23
- console.log(reactivePerson.age); // 获取 age: 23
如果你不需要跟踪对象中的所有字段,可以使用 Object.defineProperty 或一组 Object.defineProperties 来选择特定的一个或几个。
- const person = {
- _originalName: 'Pavel', // 私有属性
- }
-
- Object.defineProperty(person, 'name', {
- get() {
- console.log('获取属性 name')
- return this._originalName
- },
- set(value) {
- console.log(`将属性 name 设置为值 ${value}`)
- this._originalName = value
- },
- })
-
- console.log(person.name) // '获取属性 name' 和 'Pavel'
- person.name = 'Sergei' // 将属性 name 设置为值 Sergei
在 DOM 中实现响应性的一种方法是使用 MutationObserver。其 API 允许我们观察目标元素及其子元素的属性变化和文本内容变化。
- function handleMutations(mutationsList, observer) {
- mutationsList.forEach((mutation) => {
- // 观察到的元素的一个属性发生了变化
- if (mutation.type === 'attributes') {
- console.log(`属性 '${mutation.attributeName}' 更改为 '${mutation.target.getAttribute(mutation.attributeName)}'`);
- }
- });
- }
-
- const observer = new MutationObserver(handleMutations);
- const targetElement = document.querySelector('.element-to-observe');
-
- // 开始观察目标元素
- observer.observe(targetElement, { attributes: true });
IntersectionObserver API 允许对目标元素与另一个元素或视口区域的交集做出反应。
- function handleIntersection(entries, observer) {
- entries.forEach((entry) => {
- // 目标元素在视口中
- if (entry.isIntersecting) {
- entry.target.classList.add('visible');
- } else {
- entry.target.classList.remove('visible');
- }
- });
- }
-
- const observer = new IntersectionObserver(handleIntersection);
- const targetElement = document.querySelector('.element-to-observe');
-
- // 开始观察目标元素
- observer.observe(targetElement);
感谢阅读!
最后: