LoginSignup
4
6

More than 5 years have passed since last update.

イベントリスナを実装してみる。

Last updated at Posted at 2015-08-01

プロトタイプでイベント定義していくやつ使いどころがよくわからなかったのがだんだん見えてきたのでメモ。

オブジェクトに汎用性が出てくるのでうまく使えたら便利かもしれない。

var timer  = null;
var timer2 = null;

window.addEventListener("load", function()
{
  timer = new Timer();
  timer.addEventListener("f",  function(time){ console.log(time + ": fizz"); });
  timer.addEventListener("b",  function(time){ console.log(time + ": buzz"); });
  timer.addEventListener("fb", function(time){ console.log(time + ": fizzbuzz"); });
  timer.start();

  setTimeout(function()
  {
    timer2 = new Timer();
    timer2.addEventListener("f",  function(time){ console.log(time + ": fizz!"); });
    timer2.addEventListener("b",  function(time){ console.log(time + ": buzz!"); });
    timer2.addEventListener("fb", function(time){ console.log(time + ": fizzbuzz!"); });
    timer2.start();
  }, 500);
});

function Timer()
{
  this.time = 0;
  this.events = {};
}
Timer.prototype.start = function()
{
  var _this = this;

  setInterval(function()
  {
    _this.time = _this.time + 1;

    if(_this.time % 15 == 0)     _this.trigger("fb", _this.time);
    else if(_this.time % 5 == 0) _this.trigger("b" , _this.time);
    else if(_this.time % 3 == 0) _this.trigger("f" , _this.time);
  }, 1000);
};
Timer.prototype.addEventListener = function(key, func)
{
  this.events[key] = func;
};
Timer.prototype.trigger = function(key, arg)
{
  if(!this.events[key]) return;
  this.events[key](arg);
};

出力。延々とfizzbuzzを出力する。実際動かしてみるとはりあってる感じでちょっとかわいい。

3: fizz
3: fizz!
5: buzz
5: buzz!
6: fizz
6: fizz!
9: fizz
9: fizz!
10: buzz
10: buzz!
12: fizz
12: fizz!
15: fizzbuzz
15: fizzbuzz!
18: fizz

気をつけないといけないのは。prototypeの定義が呼び出しより後になっていると動かない。function Hoge(){}の定義の流れでprototypeも定義しがちなのでちょくちょく引っかかる。

NG(barは定義されていません。)

var foo = new Foo();
foo.bar();

function Foo(){ /* variables */ }
Foo.prototype.bar = function(){ /* process */ };

OK

function Foo(){ /* variables */ }
Foo.prototype.bar = function(){ /* process */ };

var foo = new Foo();
foo.bar();
4
6
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
4
6