Teach you how to implement the observer mode in Javascript

Teach you how to implement the observer mode in Javascript

What is the Observer Pattern?

  • Observer pattern is a design pattern.
  • The observer pattern defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified and automatically updated.
  • To put it simply, in the observer pattern, there are two models, an observer and an observed. When the observed object changes or transforms, the observer is notified.

Scenario simulation

  • If Double 11 is coming, people who want to buy goods on Double 11 are observers.
  • The product you want to buy is the observed
  • To make it more vivid, add a merchant to change the price of the product. The merchant is also the publisher (Publish)
  • On the day of Double 11, the merchant (Publisher) will modify the price of the product (Observed), and then the person who subscribes to the product (Observer) will receive a notification.

insert image description here

Code Implementation

//Observer design pattern //Publisher-->Merchant var shopObj = {};
//Product list [key:[]], key is the product name shopObj.list = [];
//Subscription method shopObj.listen = function ( key, fn) { // key is the product model, fn is the subscription behavior if (!this.list[key]) {
        this.list[key] = [];
    }
    this.list[key].push(fn); //Add a subscription to the product list with the product name key}
//Publish message method shopObj.publish = function (key) {
    //var key = arguments[0]; //If you don't pass the parameter key, you can also do this var fns = this.list[key];
    // for (var i = 0; i < fns.length; i++) {
        for(var i = 0 ,fn; fn = fns[i++];){
        //Execute the subscribed function fn arguemnts to store all arguments // var fn = fns[i++];
        fn.apply(this, arguments)
    }
}
// User A adds a subscriptionshopObj.listen("Huawei", function (brand, model) {
    console.log("User A received: " + brand + model + "The price of the mobile phone has been reduced");
})
// User B adds subscription shopObj.listen("Huawei", function (brand, model) {
    console.log("User B received: " + brand + model + "The price of the mobile phone has been reduced");
})
//c user adds subscriptionshopObj.listen("小米", function (brand, model) {
    console.log("User C received: " + brand + model + "The price of the mobile phone has been reduced");
})
//Double 11 merchants publish information about Huawei's price cutsshopObj.publish("Huawei", "p30");
shopObj.publish("小米", "Mix4");

insert image description here

Refactoring the code

//Observer design pattern var Eevent = {
    //Product list [key:[]], key is the product name list: [],
    //Subscription method listen: function (key, fn) { // key is the product model, fn is the subscription behavior if (!this.list[key]) {
            this.list[key] = [];
        }
        this.list[key].push(fn);
    },
    //Publish message method publish: function (key) {
        //var key = arguments[0]; //If you don't pass the parameter key, you can also do this var fns = this.list[key];
        // for (var i = 0; i < fns.length; i++) {
        for (var i = 0, fn; fn = fns[i++];) {
            //Execute the subscribed function fn arguemnts to store all arguments // var fn = fns[i++];
            fn.apply(this, arguments)
        }
    }
}
//Observer object initialization var initEvent = function (obj) {
    for (var i in Eevent) {
        obj[i] = Eevent[i];
    }
}
//Publisher->Merchant var shopObj = {};
initEvent(shopObj);
// User A adds a subscriptionshopObj.listen("Huawei", function (brand, model) {
    console.log("User A received: " + brand + model + "The price of the mobile phone has been reduced");
})
// User B adds subscription shopObj.listen("Huawei", function (brand, model) {
    console.log("User B received: " + brand + model + "The price of the mobile phone has been reduced");
})
//c user adds subscriptionshopObj.listen("小米", function (brand, model) {
    console.log("User C received: " + brand + model + "The price of the mobile phone has been reduced");
})
//Double 11 merchants publish information about Huawei's price cutsshopObj.publish("Huawei", "p30");
shopObj.publish("小米", "Mix4");

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Introduction and use of js observer mode
  • How to implement the observer pattern in JavaScript
  • js observer mode bullet screen case
  • JavaScript design pattern: observer mode and publish-subscribe mode detailed explanation
  • JavaScript Design Patterns – Observer Pattern Principles and Usage Examples
  • Simple example of observer and subscriber mode implemented in native js
  • JavaScript Observer Pattern Principles and Usage Examples

<<:  Analysis of the process of publishing and deploying Spring Boot applications through Docker

>>:  6 tips for web design

Recommend

JavaScript array reduce() method syntax and example analysis

Preface The reduce() method receives a function a...

CSS and JS to achieve romantic meteor shower animation

1. Rendering 2. Source code HTML < body > &...

How to run MySQL using docker-compose

Directory Structure . │ .env │ docker-compose.yml...

Detailed explanation of overflow-scrolling to solve scrolling lag problem

Preface If you use the overflow: scroll attribute...

Detailed explanation of the relationship between Linux and GNU systems

Table of contents What is the Linux system that w...

Ideas and codes for realizing magnifying glass effect in js

This article example shares the specific code of ...

Summary of basic usage of $ symbol in Linux

Linux version: CentOS 7 [root@azfdbdfsdf230lqdg1b...

What magical uses does CSS filter have

background Basic Concepts CSS filter property app...

Methods for defragmenting and reclaiming space in MySQL tables

Table of contents Causes of MySQL Table Fragmenta...

A brief introduction to MySQL dialect

Putting aside databases, what is dialect in life?...

Example of using #include file in html

There are two files a.htm and b.htm. In the same d...

MySQL green decompression version installation and configuration steps

Steps: 1. Install MySQL database 1. Download the ...

Detailed explanation of Mencached cache configuration based on Nginx

Introduction Memcached is a distributed caching s...