javascript观察者模式

javascript观察者模式学习笔记

原文地址

首先是观察者模式代码


// 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;

在观察着模式的运用当中。react组件间的通信会变得异常简单,而且可以减少组件间的耦合。


import eventProxy from '../eventProxy'

class Parent extends Component{
  render() {
    return (
      
); } } // componentDidUpdate 与 render 方法与上例一致 class Child_1 extends Component{ componentDidMount() { setTimeout(() => { // 发布 msg 事件 eventProxy.trigger('msg', 'end'); }, 1000); } } // componentDidUpdate 方法与上例一致 class Child_2 extends Component{ state = { msg: 'start' }; componentDidMount() { // 监听 msg 事件 eventProxy.on('msg', (msg) => { this.setState({ msg }); }); } render() { return

child_2 component: {this.state.msg}

} }

你可能感兴趣的:(javascript观察者模式)