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

JavaScript Design Patterns: The Observer Pattern

Feb 16, 2025 am 11:00 AM

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>
Copy after login
Copy after login
Copy after login
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

class EventObserver {
  constructor() {
    this.observers = [];
  }
}
Copy after login
Copy after login
Copy after login
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:

subscribe(fn) {
  this.observers.push(fn);
}
Copy after login
Copy after login
Copy after login
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>
Copy after login
Copy after login
Copy after login

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:

class EventObserver {
  constructor() {
    this.observers = [];
  }
}
Copy after login
Copy after login
Copy after login

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:

subscribe(fn) {
  this.observers.push(fn);
}
Copy after login
Copy after login
Copy after login

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:

// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);
Copy after login

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:

unsubscribe(fn) {
  this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}
Copy after login

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:

// Arrange
const observer = new EventObserver();
const fn = () => {};

observer.subscribe(fn);

// Act
observer.unsubscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 0);
Copy after login
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>
Copy after login
Copy after login
Copy after login

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:

class EventObserver {
  constructor() {
    this.observers = [];
  }
}
Copy after login
Copy after login
Copy after login

Then there is the following JavaScript:

subscribe(fn) {
  this.observers.push(fn);
}
Copy after login
Copy after login
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles