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.
Event Observer
The advanced view of this mode is as follows:
<code>EventObserver │ ├── subscribe: 添加新的可观察事件 │ ├── unsubscribe: 移除可观察事件 │ └── broadcast: 使用绑定数据执行所有事件</code>
, do the following: EventObserver
class EventObserver { constructor() { this.observers = []; } }
. EventObserver
subscribe method
To add a new event, do the following:
subscribe(fn) { this.observers.push(fn); }
<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:
class EventObserver { constructor() { this.observers = []; } }
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); }
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);
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); }
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);
<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:
class EventObserver { constructor() { this.observers = []; } }
Then there is the following JavaScript:
subscribe(fn) { this.observers.push(fn); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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.

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 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 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.

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

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.

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.
