|
Post by account_disabled on Jan 28, 2024 8:10:12 GMT
在 JavaScript 中,有一个经常出现的问题。您需要一种方法来更新页面的某些部分,以响应某些事件以及这些事件提供的数据。例如,您可以将用户输入投影到一个或多个组件中。这会导致代码中进行大量的推拉操作以保持所有内容同步。 Backward Skip 10s Play Video Forward Skip 10s 这就是观察者设计模式可以提供帮助的地方——它支持元素之间的一对多数据绑定。这种单向数据绑定可以是事件驱动的。使用此模式,您可以构建可重用的代码来解决您的特定需求。 在本文中,我想探讨观察者设计模式。它将帮助您解决在客户端脚本编写中遇到的常见问题。这是一对多、单向、事件驱动的数据绑定。当您有许多必须同步的元素时,这是一个经常出现的问题。 我将使用 ECMAScript 6 来说明该模式。是的,会有类、箭头函数和常量。如果您还不熟悉,请随意自行探索这些主题。我将使用 ES6 中仅引入语法糖的部分,因此如果需要,它可以与 ES5 一起移植。 我将使用测试驱动开发 (TDD) 来处理该模式。这样您就可以了解每个组件的用途。 ES6 中的新语言功能使得代码更加简洁。那么,让我们开始吧。 Learn to Code with JavaScript 事件观察者 该模式的高级视图如下所示: EventObserver subscribe: adds new observable events unsubscribe: removes observable events | └── broadcast: executes all events with bound data 在充实观察者模式后,我将添加使用它的字数 WhatsApp 号码数据 统计。字数统计组件将采用该观察者并将其整合在一起。 要初始化执行以下EventObserver操作从观察到的事件的空列表开始,并对每个新实例执行此操作。从现在开始,让我们在内部添加更多方法EventObserver来充实设计模式。 订阅方法 要添加新事件,请执行以下操作:获取观察到的事件列表并将新项目推送到数组中。事件列表是回调函数列表。 在纯 JavaScript 中测试此方法的一种方法如下我使用Node 断言在 Node 中测试这个组件。与Chai 的断言完全相同的断言也存在。 请注意,观察到的事件列表由简单的回调组成。然后我们检查列表的长度并断言回调在列表中。 取消订阅方法 要删除事件,请执行以下操作 从列表中过滤掉与回调函数匹配的内容。如果没有匹配,回调将保留在列表中。过滤器返回一个新列表并重新分配观察者列表。 要测试这个好方法,请执行以下操作 回调必须与列表中的相同函数匹配。如果存在匹配项,取消订阅方法会将其从列表中删除。请注意,测试使用函数引用来添加和删除它。 广播法 要调用所有事件,请执行以下操作: 这会迭代观察到的事件列表并执行所有回调。这样,您就可以获得与订阅事件必要的一对多关系。您传入data使回调数据绑定的参数。 ES6 通过箭头函数使代码更加有效。请注意完成大部分工作的函数。这一单行箭头函数受益于这种简短的 ES6 语法。这是 JavaScript 编程语言的显着改进。 要测试此广播方法,请执行以下操作使用let而不是 aconst这样我们就可以更改变量的值。这使得变量可变,这允许我在回调内部重新分配它的值。let在代码中使用 a会向其他程序员发送一个信号,表明该变量在某个时刻正在发生变化。这增加了 JavaScript 代码的可读性和清晰度。
|
|