Created
November 29, 2011 05:36
-
-
Save ishiduca/1403579 to your computer and use it in GitHub Desktop.
EventEmitterでイベントハンドラー ;; 3の付く数字と3の倍数の時だけアホになるタイマー
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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
出力--
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