原生js實(shí)現(xiàn)的觀察者和訂閱者模式簡(jiǎn)單示例
本文實(shí)例講述了原生js實(shí)現(xiàn)的觀察者和訂閱者模式。分享給大家供大家參考,具體如下:
觀察者模式也叫 發(fā)布者-訂閱者模式,發(fā)布者發(fā)布事件,訂閱者監(jiān)聽事件并做出反應(yīng)
在傳統(tǒng)的前端解耦方面,觀察者模式作為比較常見一種設(shè)計(jì)模式,大量使用在各種框架類庫(kù)的設(shè)計(jì)當(dāng)中。
核心代碼:
// 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;
使用:引入全局事件類,或通過(guò)配置webpack將事件類設(shè)置為全局變量
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(() => { // 發(fā)布 msg 事件 console.log(eventProxy) eventProxy.trigger(’msg’, ’end’,’lll’); }, 5000); } render() { return ( <div>我是組件一</div> ) }}// componentDidUpdate 方法與上例一致class Child_2 extends Component{ state = { msg: ’start’ }; componentDidMount() { // 監(jiān)聽 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> }}
參考:淘寶前端團(tuán)隊(duì)技術(shù)庫(kù)
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試上述代碼運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《javascript面向?qū)ο笕腴T教程》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖3. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車4. Python 中如何使用 virtualenv 管理虛擬環(huán)境5. Python獲取B站粉絲數(shù)的示例代碼6. Python基于requests實(shí)現(xiàn)模擬上傳文件7. python利用opencv實(shí)現(xiàn)顏色檢測(cè)8. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題9. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)10. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效
