JSFiddle - React, Tailwind, and code Playground

by ken3desu

HTML

<div class="flex">
  <div>event:</div><div class="event-box"></div>
</div>
<button class="update-btn">値をMath.randomで変更</button>

CSS

.flex {
 display: flex;
}

JavaScript

/**
 * 値を監視する機能を持った値を表現するオブジェクト
 */
class ValueWithEventListener {
  /**
   * 初期化。
   */
  constructor(initVal, event) {
    this._oldVal = initVal;
    this._curVal = initVal;
    this._event = event;
  }

  /**
   * セッター。以前と異なる値がセットされた時にイベントを発生させる
   * @param {T} newVal
   */
  set val(newVal) {
    this._oldVal = this._curVal;
    this._curVal = newVal;
    if (this._oldVal !== this._curVal) {
      // ここに変化を検知した時のイベントを追加
      this._event(newVal);
    }
  }

  /**
   * ゲッター。外部からは自然に読み取れるようにする
   */
  get val() {
    return this._curVal;
  }
}

const val = new ValueWithEventListener(12,(newVal)=>{
	document.querySelector('.event-box').innerText = newVal;
});

document.querySelector('.update-btn')
	.addEventListener('click',()=>val.val = Math.random()+' in btn')