Last active
August 29, 2015 14:25
-
-
Save hkusu/c137ab572ea2d2afb0ec to your computer and use it in GitHub Desktop.
ES6 の Proxy によるデータの変更通知の例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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