原生js實現的觀察者和訂閱者模式簡單示例
阿新 • • 發佈:2020-04-20
本文例項講述了原生js實現的觀察者和訂閱者模式。分享給大家供大家參考,具體如下:
觀察者模式也叫 釋出者-訂閱者模式,釋出者釋出事件,訂閱者監聽事件並做出反應
在傳統的前端解耦方面,觀察者模式作為比較常見一種設計模式,大量使用在各種框架類庫的設計當中。
核心程式碼:
// eventProxy.js 'use strict'; const eventProxy = { onObj: {},oneObj: {},on: function(key,fn) { if(this.onObj[key] === undefined) { this.onObj[key] = []; } this.onObj[key].push(fn); },one: function(key,fn) { if(this.oneObj[key] === undefined) { this.oneObj[key] = []; } this.oneObj[key].push(fn); },off: function(key) { this.onObj[key] = []; this.oneObj[key] = []; },trigger: function() { let key,args; if(arguments.length == 0) { return false; } key = arguments[0]; args = [].concat(Array.prototype.slice.call(arguments,1)); if(this.onObj[key] !== undefined && this.onObj[key].length > 0) { for(let i in this.onObj[key]) { this.onObj[key][i].apply(null,args); } } if(this.oneObj[key] !== undefined && this.oneObj[key].length > 0) { for(let i in this.oneObj[key]) { this.oneObj[key][i].apply(null,args); this.oneObj[key][i] = undefined; } this.oneObj[key] = []; } } }; export default eventProxy;
使用:引入全域性事件類,或通過配置webpack將事件類設定為全域性變數
import { eventProxy } from '@/utils' class Parent extends Component{ render() { return ( <div style={{marginTop:"50px"}}> <Child_1/> <Child_2/> </div> ); } } // componentDidUpdate 與 render 方法與上例一致 class Child_1 extends Component{ componentDidMount() { setTimeout(() => { // 釋出 msg 事件 console.log(eventProxy) eventProxy.trigger('msg','end','lll'); },5000); } render() { return ( <div>我是元件一</div> ) } } // componentDidUpdate 方法與上例一致 class Child_2 extends Component{ state = { msg: 'start' }; componentDidMount() { // 監聽 msg 事件 eventProxy.on('msg',(msg,mm) => { console.log(msg,mm) this.setState({ msg:msg }); }); } render() { return <div> <p>child_2 component: {this.state.msg}</p> </div> } }
參考:淘寶前端團隊技術庫
感興趣的朋友可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。
更多關於JavaScript相關內容感興趣的讀者可檢視本站專題:《javascript面向物件入門教程》、《JavaScript錯誤與除錯技巧總結》、《JavaScript資料結構與演算法技巧總結》、《JavaScript遍歷演算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程式設計有所幫助。