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

Example of using CSS3 to create Pikachu animated wallpaper

text OK, next it’s time to show the renderings. O...

MySQL complete collapse: detailed explanation of query filter conditions

Overview In actual business scenario applications...

Detailed explanation of MySQL transactions and MySQL logs

Transactional Characteristics 1. Atomicity: After...

MySql Group By implements grouping of multiple fields

In daily development tasks, we often use MYSQL...

HTML table markup tutorial (14): table header

<br />In HTML language, you can automaticall...

Detailed explanation of the functions of each port of Tomcat

From the tomcat configuration file, we can see th...

Detailed use cases of MySql escape

MySQL escape Escape means the original semantics ...

Detailed explanation and summary of the URL for database connection

Detailed explanation and summary of the URL for d...

Method of implementing recursive components based on Vue technology

describe This article introduces a method to impl...

Complete steps for Nginx to configure anti-hotlinking

need: Usually, sites want to prevent videos and p...

A brief discussion on VUE uni-app template syntax

1.v-bind (abbreviation:) To use data variables de...