1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavascriptでスマートにObservableする 改

Last updated at Posted at 2017-12-06

前回

スマートだと思っていたらスマートじゃなかった
https://qiita.com/angeart/items/c1ec1c59b66d5b57773a

やりたいこと

javascriptでMVVMのObservableのような通知を送る実装を書きたい

継承を利用してもっとスマートに

前回は利用クラスのconstructorの中でObservableクラスに包みましたが
よくよく考えたらinstanceofが利用出来ないですし、別物のクラスとして実体化してしまうのでスマートじゃないです
なので継承で利用できるようにしました。

実装

var $ = require('jquery');
class Observable {
  constructor() {
    return new Proxy(this, {
      set: function(obj, prop, value) {
        if (obj[prop] === value) return true;
        obj[prop] = value;
        $(obj).trigger("onchanged", {
          prop: prop
        });
        return true;
      }
    });
  }
}

class Test extends Observable {
  constructor() {
    super();
    $(this).on("onchanged", function(e, data) {
      console.log("changed : " + this[data.prop]);
    });
  }
}

var tester = new Test();

tester.hoge = "hoge";
tester.hoge = "hoge";
tester.hoge = "fuga";

if (tester instanceof Test) {
  console.log("ok");
}

イベントの設定にjQueryを用いています

実行結果

changed : hoge
changed : fuga
ok

#repl.it
https://repl.it/@Angeart/Observable-on-Javascript-2

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?