javascript觀察者模式

javascript觀察者模式學(xué)習(xí)筆記

原文地址

首先是觀察者模式代碼


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

在觀察著模式的運(yùn)用當(dāng)中。react組件間的通信會(huì)變得異常簡(jiǎn)單,而且可以減少組件間的耦合。


import eventProxy from '../eventProxy'

class Parent extends Component{
  render() {
    return (
      <div>
        <Child_1/>
        <Child_2/>
      </div>
    );
  }
}
// componentDidUpdate 與 render 方法與上例一致
class Child_1 extends Component{
  componentDidMount() {
    setTimeout(() => {
      // 發(fā)布 msg 事件
      eventProxy.trigger('msg', 'end');
    }, 1000);
  }
}
// componentDidUpdate 方法與上例一致
class Child_2 extends Component{
  state = {
    msg: 'start'
  };

  componentDidMount() {
    // 監(jiān)聽 msg 事件
    eventProxy.on('msg', (msg) => {
      this.setState({
        msg
      });
    });
  }

  render() {
    return <div>
      <p>child_2 component: {this.state.msg}</p>
      <Child_2_1 />
    </div>
  }
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,228評(píng)論 25 708
  • 簡(jiǎn)單理解邏輯: A發(fā)布一個(gè)消息 ,如果B,C,D都訂閱了這個(gè)事件,則會(huì)將所有訂閱著訂閱的消息依此執(zhí)行。 常見(jiàn)的使用...
    麥子_FE閱讀 265評(píng)論 0 0
  • 開水在受涼 酒香在醞釀 智齒在生長(zhǎng) 人在臥鋪上搖搖晃晃 我說(shuō)我喜歡慢時(shí)光 幸福就與我捉迷藏 2016.6.11
    夾餡鍋鍋閱讀 183評(píng)論 0 0
  • 生命猶如星空下的繁星,密密麻麻的點(diǎn)綴漆黑的夜空,然而不管它是無(wú)窮無(wú)盡的數(shù)量,還是無(wú)止境的輪轉(zhuǎn),生命對(duì)于每個(gè)人都只有...
    雄雞小建閱讀 265評(píng)論 1 2
  • 一些定義 數(shù)據(jù)庫(kù)(database):保存有組織的數(shù)據(jù)的容器; 數(shù)據(jù)庫(kù)軟件:DBMS(數(shù)據(jù)庫(kù)管理系統(tǒng)); 數(shù)據(jù)庫(kù)是...
    olivia_ong閱讀 660評(píng)論 0 0

友情鏈接更多精彩內(nèi)容