1. 程式人生 > >原生js實現觀察者和訂閱者模式

原生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>
  }
}

參考:淘寶前端團隊技術庫