SoFunction
Updated on 2025-04-07

Simple example of observer and subscriber pattern for native js implementation

This article describes the observer and subscriber patterns of native js implementation. Share it for your reference, as follows:

Observer mode is also called Publisher-Subscriber mode, Publisher publishes events, subscribers listen to events and react

In terms of traditional front-end decoupling, the observer mode is a relatively common design pattern and is widely used in the design of various framework library.

Core code:

// 
'use strict';
const eventProxy = {
 onObj: {},
 oneObj: {},
 on: function(key, fn) {
  if([key] === undefined) {
   [key] = [];
  }
 
  [key].push(fn);
 },
 one: function(key, fn) {
  if([key] === undefined) {
   [key] = [];
  }
 
  [key].push(fn);
 },
 off: function(key) {
  [key] = [];
  [key] = [];
 },
 trigger: function() {
  let key, args;
  if( == 0) {
   return false;
  }
  key = arguments[0];
  args = [].concat((arguments, 1));
 
  if([key] !== undefined
   && [key].length > 0) {
   for(let i in [key]) {
    [key][i].apply(null, args);
   }
  }
  if([key] !== undefined
   && [key].length > 0) {
   for(let i in [key]) {
    [key][i].apply(null, args);
    [key][i] = undefined;
   }
   [key] = [];
  }
 }
};
 
export default eventProxy;

Use: Introduce global event class, or set event class as global variable by configuring webpack

import { eventProxy } from '@/utils'
 
class Parent extends Component{
 render() {
  return (
   <div style={{marginTop:"50px"}}>
    <Child_1/>
    <Child_2/>
   </div>
  );
 }
}
// componentDidUpdate and render methods are consistent with the previous exampleclass Child_1 extends Component{
 componentDidMount() {
  setTimeout(() => {
   // Publish msg event   (eventProxy)
   ('msg', 'end','lll');
  }, 5000);
 }
 render() {
  return (
   <div>I'm component one</div>
  )
 }
}
// componentDidUpdate method is consistent with the previous exampleclass Child_2 extends Component{
 state = {
  msg: 'start'
 };
 
 componentDidMount() {
  // Listen to msg events  ('msg', (msg,mm) => {
   (msg,mm)
   ({
    msg:msg
   });
  });
 }
 
 render() {
  return <div>
   <p>child_2 component: {}</p>
  </div>
 }
}

Reference: Taobao Front-end Team Technology Library

Interested friends can use itOnline HTML/CSS/JavaScript code running toolhttp://tools./code/HtmlJsRunTest the above code running effect.

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript traversal algorithm and skills"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.