counter.js 570 B

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