Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created November 29, 2011 05:36
Show Gist options
  • Save ishiduca/1403579 to your computer and use it in GitHub Desktop.
Save ishiduca/1403579 to your computer and use it in GitHub Desktop.
EventEmitterでイベントハンドラー ;; 3の付く数字と3の倍数の時だけアホになるタイマー
var EvEm = require('events').EventEmitter;
function Timer (interval, defaultFunc) {
this.count = 0;
this.interval = interval || 1000; // 1秒デフォルト
this.eventsList = {};
this.default = defaultFunc || function (c) { console.log(c); };
};
(function (_tp) {
_tp.setEmt = function (emtName, pattern) {
this.eventsList[emtName] = pattern;
return this;
};
_tp.run = function () {
var that = this,
count = this.count,
eventsList = this.eventsList,
clearInt = setInterval(function () {
var flg = 0;
for (var prop in eventsList) {
if (eventsList[prop](count)) {
that.emit(prop, count);
flg++;
}
}
if (flg === 0) that.default(count);
count++;
return ;
}, this.interval);
console.log(count++);
};
})(Timer.prototype = new EvEm);
var timer = new Timer;
timer
.setEmt('aho', function (c) {
return (c % 3 === 0 || c.toString().match(/3/)) ? true : false;
})
.setEmt('dog', function (c) {
return (c % 5 === 0 || c.toString().match(/5/)) ? true : false;
})
;
timer
.on('aho', function (c) {
console.log('aho! %s', c);
}).on('dog', function (c) {
console.log('waooon!! %s', c);
})
;
timer.run();
1;
@ishiduca
Copy link
Author

出力--
0
1
2
aho! 3
4
waooon!! 5
aho! 6
7
8
aho! 9
waooon!! 10
11
aho! 12
aho! 13
14
aho! 15
waooon!! 15
16
17
aho! 18
19
waooon!! 20
aho! 21

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