Home >Web Front-end >JS Tutorial >JavaScript Design Patterns: The Observer Pattern

JavaScript Design Patterns: The Observer Pattern

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-02-16 11:00:151011browse

JavaScript Design Patterns: The Observer Pattern

Key Points of JavaScript Observer Pattern

  • Observer pattern in JavaScript allows one-to-many data binding between elements, which is especially useful for keeping multiple elements synchronized with the same data.
  • Observer pattern contains three main methods: subscribe (add new observable events), unsubscribe (remove all events using bound data). broadcast
  • Using ES6 features such as classes, arrow functions, and constants can effectively implement observer patterns, making the code simpler and easier to reuse.
  • Observer mode can be used to solve practical problems in JavaScript, such as updating word counts in blog posts at each keystroke and can be further enhanced to build new features.
In JavaScript, there is often a problem: a method is needed to update a part of the page in response to certain events and use the data provided by those events. For example, the user enters and then projects it into one or more components. This causes a lot of push and pull operations in the code to keep everything in sync. This is where the Observer Design Pattern can help - it implements one-to-many data binding between elements. This one-way data binding can be event-driven. With this pattern, you can build reusable code to address your specific needs. In this article, I want to explore the observer design pattern. It will help you solve a common problem that you often encounter in client scripts. That is one-to-many, one-way and event-driven binding. This problem often occurs when you have a lot of elements that have to be synchronized. I will use ECMAScript 6 to illustrate this pattern. Yes, there will be classes, arrow functions and constants. If you are not familiar with it, you can explore these topics yourself. I will only use the part that introduces syntactic sugar in ES6, so it can also work with ES5 if needed. I will use Test Driven Development (TDD) to handle this pattern. This way, you can know how each component is used. New language features in ES6 make the code more concise. So, let's get started.

Event Observer

The advanced view of this mode is as follows:

<code>EventObserver
│ 
├── subscribe: 添加新的可观察事件
│ 
├── unsubscribe: 移除可观察事件
│
└── broadcast: 使用绑定数据执行所有事件</code>
After elaborating on the Observer mode, I will add a word counting feature that uses it. The Word Count component will use this observer and integrate everything together. To initialize

, do the following: EventObserver

<code class="language-javascript">class EventObserver {
  constructor() {
    this.observers = [];
  }
}</code>
Start with an empty list of observation events, and each new instance does so. From now on, let's add more ways to perfect the design pattern in

. EventObserver

subscribe method

To add a new event, do the following:

<code class="language-javascript">subscribe(fn) {
  this.observers.push(fn);
}</code>
Get the list of observation events and push new items into the array. The event list is a callback function list. One way to test this method in pure JavaScript is as follows:

<code>EventObserver
│ 
├── subscribe: 添加新的可观察事件
│ 
├── unsubscribe: 移除可观察事件
│
└── broadcast: 使用绑定数据执行所有事件</code>

I use Node assertion to test this component in Node. The exact same assertion also exists in the Chai assertion. Note that the observation event list consists of simple callbacks. We then check the length of the list and assert that the callback is in the list.

unsubscribe method

To remove an event, do the following:

<code class="language-javascript">class EventObserver {
  constructor() {
    this.observers = [];
  }
}</code>

Filter out anything that matches the callback function from the list. If there is no match, the callback will remain in the list. The filter returns a new list and reassigns the observer list. To test this good method, do the following:

<code class="language-javascript">subscribe(fn) {
  this.observers.push(fn);
}</code>

The callback must match the same function on the list. If a match exists, the unsubscribe method removes it from the list. Note that the test uses function reference to add and remove it.

broadcast method

To call all events, do the following:

<code class="language-javascript">// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);</code>

This will iterate over the list of observation events and execute all callbacks. With this you can get the one-to-many relationship you need to subscribe to events. You can pass in the data parameter, which makes the callback data binding. ES6 uses arrow functions to make the code more efficient. Note that the (subscriber) => subscriber(data) function does most of the work. This single-line arrow function benefits from this short ES6 syntax. This is a significant improvement in the JavaScript programming language. To test this broadcast method:

<code class="language-javascript">unsubscribe(fn) {
  this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}</code>

Use let instead of const so that we can change the value of the variable. This makes the variable mutable, allowing me to reassign its value in the callback. Use let in your code to signal to other programmers that the variable is changing at some point. This increases the readability and clarity of JavaScript code. This test gives me enough confidence to make sure the observer works as expected. With TDD, it's all about building reusable code in pure JavaScript. There are many benefits to writing testable code in pure JavaScript. Test everything and keep what is beneficial for code reuse. With this, we have perfected it. The question is, what can you build with it? EventObserver

Practical application of observer mode: blog word count demonstration

For the demo, it's time to create a blog post that keeps word count for you. Each keystroke you enter will be synchronized by the Observer Design Pattern. Think of it as free text input, where each event triggers an update to where you need it to go. To get word count from free text input, you can do the following:

<code class="language-javascript">// Arrange
const observer = new EventObserver();
const fn = () => {};

observer.subscribe(fn);

// Act
observer.unsubscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 0);</code>
Completed! There is a lot of content in this seemingly simple pure function, so how about a simple unit test? In this way, my intentions are clear:

<code>EventObserver
│ 
├── subscribe: 添加新的可观察事件
│ 
├── unsubscribe: 移除可观察事件
│
└── broadcast: 使用绑定数据执行所有事件</code>

Please note the slightly weird input string in blogPost. My goal is to have this function cover as many edge cases as possible. As long as it gives me a correct word count, we go in the right direction. By the way, this is the real power of TDD. This implementation can be iterated and covers as many use cases as possible. Unit tests tell you how I expect it to behave. If the behavior is flawed, it is easy to iterate and adjust it for whatever reason. By testing, leave enough evidence for others to make the changes. It's time to connect these reusable components to the DOM. This is the part you take pure JavaScript and solder it into your browser. One way is to use the following HTML on the page:

<code class="language-javascript">class EventObserver {
  constructor() {
    this.observers = [];
  }
}</code>

Then there is the following JavaScript:

<code class="language-javascript">subscribe(fn) {
  this.observers.push(fn);
}</code>

Get all reusable code and set observer design mode. This will track changes in the text area and give you word count below it. I'm using body.appendChild() in the DOM API to add this new element. Then, an event listener is attached to bring it to life. Note that using arrow functions can connect a single line of events. In fact, you can use it to broadcast event-driven changes to all subscribers. () => blogObserver.broadcast()Most of the work was done here. It even passes the latest changes to the text area directly into the callback function. Yes, client scripts are pretty cool. None of the demos you can touch and adjust is complete, here is the CodePen: (The CodePen link should be inserted here, which cannot be provided due to the inability to access external websites)

Now, I won't call this feature a full feature. But this is just the starting point for the observer's design pattern. The question in my mind is, how far are you willing to go?

Looking forward

You can develop this idea further. You can use the Observer Design Pattern to build many new features. You can enhance the demo using the following methods:

  • Another component calculates the number of paragraphs
  • Another component displays a preview of the input text
  • Enhanced previews with markdown support, e.g.

These are just some ideas you can dig into. The above enhancements will challenge your programming capabilities.

Conclusion

Observer design pattern can help you solve practical problems in JavaScript. This solves the long-term problem of keeping a bunch of elements in sync with the same data. Typically, when the browser triggers a specific event. I believe most of you have had this problem now and have turned to tools and third-party dependencies. This design pattern allows you to go as far as possible. In programming, you abstract the solution into patterns and build reusable code. The benefits this will bring to you are endless. I hope you can see how much work you can do in pure JavaScript with just a little discipline and effort. New features in the language, such as ES6, can help you write some concise and reusable code.

(The FAQ for JavaScript Observer Pattern should be included here, but due to space limitations, it has been omitted.)

The above is the detailed content of JavaScript Design Patterns: The Observer Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn