


JavaScript observer pattern definition and detailed explanation of scene instance code
Observer Pattern
Define a one-to-many dependency relationship between objects so that when the state of an object changes, all objects that depend on it are notified And automatically refresh, also known as the publish-subscribe model.
It requires a high-level abstraction strategy so that subscribers can change independently of each other, and the issuer can accept any subscriber with consumption intention.
Application scenarios:
This model should first talk about the application scenarios, which is easier to understand.
Let’s take a scene that is relatively close to us. There is a subscription button in the blog park (it seems to have a bug). For example, Little A, Little B, and Little C have all subscribed to my blog and become my blog. Whenever there is an update, an email will be published to these three people, and these subscribers will be notified
The process of publishing and subscribing model is as follows:
1. Determine who is the publisher (such as my blog).
2. Then add a cache list to the publisher to store callback functions to notify subscribers.
3. To publish a message, the publisher needs to traverse this cache list and trigger the subscriber callback functions stored in it in turn.
4. Unsubscribe (for example, if you no longer want to receive these subscription information, you can cancel it)
The code is as follows:
var pubsub = {}; // 定义发布者 (function (q) { var list = [], //回调函数存放的数组,也就是记录有多少人订阅了我们东西 subUid = -1; // 发布消息,遍历订阅者 q.publish = function (type, content) { // type 为文章类型,content为文章内容 // 如果没有人订阅,直接返回 if (!list[type]) { return false; } setTimeout(function () { var subscribers = list[type], len = subscribers ? subscribers.length : 0; while (len--) { // 将内容注入到订阅者那里 subscribers[len].func(type, content); } }, 0); return true; }; //订阅方法,由订阅者来执行 q.subscribe = function (type, func) { // 如果之前没有订阅过 if (!list[type]) { list[type] = []; } // token相当于订阅者的id,这样的话如果退订,我们就可以针对它来知道是谁退订了。 var token = (++subUid).toString(); // 每订阅一个,就把它存入到我们的数组中去 list[type].push({ token: token, func: func }); return token; }; //退订方法 q.unsubscribe = function (token) { for (var m in list) { if (list[m]) { for (var i = 0, j = list[m].length; i < j; i++) { if (list[m][i].token === token) { list[m].splice(i, 1); return token; } } } } return false; }; } (pubsub)); //将订阅赋值给一个变量,以便退订 var girlA = pubsub.subscribe('js类的文章', function (type, content) { console.log('girlA订阅的'+type + ": 内容内容为:" + content); }); var girlB = pubsub.subscribe('js类的文章', function (type, content) { console.log('girlB订阅的'+type + ": 内容内容为:" + content); }); var girlC = pubsub.subscribe('js类的文章', function (type, content) { console.log('girlC订阅的'+type + ": 内容内容为:" + content); }); //发布通知 pubsub.publish('js类的文章', '关于js的内容'); // 输出: // girlC订阅的js类的文章: 内容内容为:关于js的内容 // test3.html:78 girlB订阅的js类的文章: 内容内容为:关于js的内容 // test3.html:75 girlA订阅的js类的文章: 内容内容为:关于js的内容 //girlA退订了关于js类的文章 setTimeout(function () { pubsub.unsubscribe(girlA); }, 0); //再发布一次,验证一下是否还能够输出信息 pubsub.publish('js类的文章', "关于js的第二篇文章"); // 输出: // girlB订阅的js类的文章: 内容内容为:关于js的第二篇文章 // girlC订阅的js类的文章: 内容内容为:关于js的第二篇文章
The code can be run by itself, so Easier to understand
Advantages and disadvantages:
Advantages: When we need to maintain the consistency of related objects, using the observer pattern can avoid tight coupling between objects. For example, one object can notify another object without knowing the information about that object.
Disadvantages: In the publish/subscribe model, if we need to decouple publishers from subscribers, it will in some cases make it difficult to ensure that specific parts of our application behave as we expect. normal work. That is to say, its advantages may also be its disadvantages
The above is the detailed content of JavaScript observer pattern definition and detailed explanation of scene instance code. For more information, please follow other related articles on the PHP Chinese website!

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


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

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
