1 | var EventEmitter = require('events').EventEmitter
|
2 |
|
3 | function Counter () {
|
4 | EventEmitter.call(this)
|
5 | this.value = 0
|
6 | }
|
7 |
|
8 | Counter.prototype = Object.create(EventEmitter.prototype)
|
9 |
|
10 | Counter.prototype.increment = function increment () {
|
11 | this.value++
|
12 | }
|
13 |
|
14 | Counter.prototype.decrement = function decrement () {
|
15 | if (--this.value === 0) this.emit('zero')
|
16 | }
|
17 |
|
18 | Counter.prototype.isZero = function isZero () {
|
19 | return (this.value === 0)
|
20 | }
|
21 |
|
22 | Counter.prototype.onceZero = function onceZero (fn) {
|
23 | if (this.isZero()) return fn()
|
24 |
|
25 | this.once('zero', fn)
|
26 | }
|
27 |
|
28 | module.exports = Counter
|