Skip to content

Instantly share code, notes, and snippets.

@naosim
Created October 15, 2024 21:01
Show Gist options
  • Save naosim/63d386edc554384dc9d5b36a90d2aa47 to your computer and use it in GitHub Desktop.
Save naosim/63d386edc554384dc9d5b36a90d2aa47 to your computer and use it in GitHub Desktop.
変更を監視する
class ChangeEventChecker {
add(name, checkerFunc) {
this[name] = {checkerFunc, lastValue:undefined, isChanged:false};
return this;
}
check() {
Object.entries(this).forEach((e) => {
const [k, v] = e;
const value = v.checkerFunc();
if(v.lastValue !== undefined) {
v.isChanged = v.lastValue != value;
}
v.lastValue = value;
})
}
}
@naosim
Copy link
Author

naosim commented Oct 15, 2024

本クラスを使わな場合

var ex = 0; // 経験値
var lv = 1; // レベル

init = function() {
}

update = function() {
  ex++; // 経験値たまる
  if(ex % 100 == 0) { // レベルが上がる
    lv++;
  }
}
var lastLv; // ★監視対象の数だけ増える
draw = function() {
  if(lastLv !== undefined && lastLv != lv) {
    // 音を鳴らす
    print("音")
  }
  lastLv = lv; // ★監視対象の数だけ増える
}

@naosim
Copy link
Author

naosim commented Oct 15, 2024

本クラスを使う場合

var ex = 0; // 経験値
var lv = 1; // レベル
var changeEventChecker;
init = function() {
  changeEventChecker = new ChangeEventChecker();
  changeEventChecker.add("lv", () => lv);// 監視対象を設定
}

update = function() {
  ex++;
  if(ex % 100 == 0) {
    lv++;
  }
}

draw = function() {
  changeEventChecker.check();
  if(changeEventChecker.lv.isChanged) {
    // 音を鳴らす
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment