search
HomeWeb Front-endJS TutorialThe front-end state manager you must master

javascript栏目教大家掌握前端状态管理器。

The front-end state manager you must master

状态管理器

随着ReactVue等异步框架的广泛运用,前端状态管理器逐渐成为前端开发比不可少话题。形如React有倍受欢迎的Redux,再如Vue标配的状态管理器Vuex,都是业内相对成熟的状态管理器,那么我们接下来就用原生javascript来实现一个状态管理器。

主要包含两个方面:第一是发布订阅,第二是状态管理

发布订阅PubSub

创建类

首先我们先创建一个PubSub类函数:

class PubSub {  constructor() {  	// 收集事件
    this.events = {};
  }
}复制代码

实现Publish

接着我们来实现一个发布函数:

class PubSub {
  ...  // 发布
  publish(event, data = {}) {    const self = this;	
    /*
     * 校验是否存在事件
     * 默认返回一个空数组
     */
    if (!self.events.hasOwnProperty(event)) {      return [];
    }	
    // 遍历执行事件队列里的回调函数
    return self.events[event].map((callback) => callback(data));
  }
  ...
}复制代码

实现Subscribe

实现完发布函数publish,接着我们来实现订阅函数:

class PubSub {
	...
    // 订阅
    subscribe(event, callback) {
      const self = this;
      
      /*
       * 校验是否存在事件
       * 默认给一个空数组
       */
      if (!self.events.hasOwnProperty(event)) {
        self.events[event] = [];
      }
	  
      // 将事件推入回调队列
      return self.events[event].push(callback);
    }
    ...
}复制代码

完整代码

class PubSub {  constructor() {    // 收集事件
    this.events = {};
  }  // 订阅
  subscribe(event, callback) {    const self = this;    /*
     * 校验是否存在事件
     * 默认给一个空数组
     */
    if (!self.events.hasOwnProperty(event)) {
      self.events[event] = [];
    }    // 将事件推入回调队列
    return self.events[event].push(callback);
  }  // 发布
  publish(event, data = {}) {    const self = this;	
    /*
     * 校验是否存在事件
     * 默认返回一个空数组
     */
    if (!self.events.hasOwnProperty(event)) {      return [];
    }	
    // 遍历执行事件队列里的回调函数
    return self.events[event].map((callback) => callback(data));
  }
}复制代码

状态管理Store

创建类

首先我们创建一个Store类函数:

class Store {	// 传入params对象
	constructor(params) {    	const self = this;

        self.actions = {}; // 异步任务对象
        self.mutations = {}; // 同步任务对象
        self.state = {}; // 全局状态对象
        self.plugins = []; // 插件
        self.status = "resting"; // 初始状态
		
        /*
         * 初始化设置actions对象
         * 该对象主要处理异步事件
         */
        if (params.hasOwnProperty("actions")) {
          self.actions = params.actions;
        }		
        /*
         * 初始化设置mutations对象
         * 该对象主要处理同步事件
         */
        if (params.hasOwnProperty("mutations")) {
          self.mutations = params.mutations;
        }        // 插件
        if (params.hasOwnProperty("plugins")) {
          self.plugins = params.plugins;
        }        /* 
         * 代理监听state
         */
        self.state = new Proxy(params.state || {}, {          set(state, key, value) {          	// 代理设置state对象并赋值
            state[key] = value;			
            // 更改状态
            self.status = "resting";            return true;
          },
        });
    }
}复制代码

实现commit

接着我们来实现核心函数commit,该函数主要处理对象更改,调用mutations对象内的函数:

class Store {
	...
    commit = (mutationKey, payload) => {      const self = this;      // 校验是否存在函数
      if (typeof self.mutations[mutationKey] !== "function") {        console.warn(`Mutation ${mutationKey} dose not exist`);        return false;
      }	  
      // 变更状态
      self.status = "mutation";      
      // 执行对应函数
      self.mutations[mutationKey](self.state, payload);      return true;
    };
    ...
}复制代码

实现dispatch

实现完commit,我们再来实现dispatch,这个函数主要处理异步问题,传入commit方法:

class Store {
	...
    dispatch = (actionKey, payload) => {      const self = this;      
      // 校验是否存在函数
      if (typeof self.actions[actionKey] !== "function") {        console.warn(`Action ${actionKey} dose not exist`);        return false;
      }	  
      // 变更状态
      self.status = "action";      
      // 执行对应函数,并传入commit
      self.actions[actionKey]({ commit: self.commit }, payload);      return true;
    };
    ...
}复制代码

完整代码

class Store {	// 传入params对象
	constructor(params) {    	const self = this;

        self.actions = {}; // 异步任务对象
        self.mutations = {}; // 同步任务对象
        self.state = {}; // 全局状态对象
        self.plugins = []; // 插件
        self.status = "resting"; // 初始状态
		
        /*
         * 初始化设置actions对象
         * 该对象主要处理异步事件
         */
        if (params.hasOwnProperty("actions")) {
          self.actions = params.actions;
        }		
        /*
         * 初始化设置mutations对象
         * 该对象主要处理同步事件
         */
        if (params.hasOwnProperty("mutations")) {
          self.mutations = params.mutations;
        }        // 插件
        if (params.hasOwnProperty("plugins")) {
          self.plugins = params.plugins;
        }        /* 
         * 代理监听state
         */
        self.state = new Proxy(params.state || {}, {          set(state, key, value) {          	// 代理设置state对象并赋值
            state[key] = value;			
            // 更改状态
            self.status = "resting";            return true;
          },
        });
   }

  dispatch = (actionKey, payload) => {      const self = this;      
      // 校验是否存在函数
      if (typeof self.actions[actionKey] !== "function") {        console.warn(`Action ${actionKey} dose not exist`);        return false;
      }	  
      // 变更状态
      self.status = "action";      
      // 执行对应函数,并传入commit
      self.actions[actionKey]({ commit: self.commit }, payload);      return true;
  }

  commit = (mutationKey, payload) => {      const self = this;      // 校验是否存在函数
      if (typeof self.mutations[mutationKey] !== "function") {        console.warn(`Mutation ${mutationKey} dose not exist`);        return false;
      }	  
      // 变更状态
      self.status = "mutation";      
      // 执行对应函数
      self.mutations[mutationKey](self.state, payload);      return true;
   }
}复制代码

PubSub和Store结合

引入PubSub库

	const SubPub = require("../lib/pubsub");    
    // 在state的代理中监测到数据改变,发布相对应事件
    class Store {    	constructor(params) {        	// 实例化发布订阅
        	self.events = new SubPub()
        
        	...            /* 
             * 代理监听state
             */
            self.state = new Proxy(params.state || {}, {              set(state, key, value) {                // 代理设置state对象并赋值
                state[key] = value;                
                // 添加发布事件
                self.events.publish("stateChange", self.state);                // 更改状态
                self.status = "resting";                return true;
              },
            });
            ...
        }
    }复制代码

实例场景

const Store = new Store({	state: {    	text: ''
    },	mutations: {    	init: (state, payload) => {
        	state.text = payload
        },
    },    actions: {    	init: ({commit},payload) => {        	setTimeout(() => {
            	commit('init', payload)
            },200)
        }
    },    plugins: [    	function() {        	console.log('plugins')
        }
    ]
})// 执行同步事件Store.commit('init', 'hello init')// 执行异步事件Store.dispatch('init', 'hello async init')复制代码

总结

以上就是基础版的全局状态管理器,包含基本的同步和异步处理,插件,发布订阅功能,当然还有些细节需要完善。有问题欢迎在评论中指出,谢谢。

Related free learning recommendations: javascript (Video)

The above is the detailed content of The front-end state manager you must master. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft