Skip to content

Instantly share code, notes, and snippets.

@hkusu
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save hkusu/c137ab572ea2d2afb0ec to your computer and use it in GitHub Desktop.

Select an option

Save hkusu/c137ab572ea2d2afb0ec to your computer and use it in GitHub Desktop.
ES6 の Proxy によるデータの変更通知の例
// Proxy 用のハンドラ
var handler = {
set: function(obj, prop, value) {
obj[prop] = value;
// 何かのプロパティの値が変更されたら onDataChange メソッドを呼び出す
if (typeof obj['onDataChange'] !== 'undefined') {
obj.onDataChange();
}
return true;
}
};
// Proson クラス
var Person = function(name, age) {
this.name = name;
this.age = age;
};
// Person クラスを Proxy 経由でインスタンス化
var person = new Proxy(new Person('Yamada', '45'), handler);
// データが変更された際に実行する処理を定義
person.onDataChange = function() {
console.log('データが変更されました');
};
// データを変更してみる
person.age = 200; // データが変更されました、が出力される
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment