batcher.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var utils = require('./utils')
  2. function Batcher () {
  3. this.reset()
  4. }
  5. var BatcherProto = Batcher.prototype
  6. BatcherProto.push = function (job) {
  7. if (!job.id || !this.has[job.id]) {
  8. this.queue.push(job)
  9. this.has[job.id] = job
  10. if (!this.waiting) {
  11. this.waiting = true
  12. utils.nextTick(utils.bind(this.flush, this))
  13. }
  14. } else if (job.override) {
  15. var oldJob = this.has[job.id]
  16. oldJob.cancelled = true
  17. this.queue.push(job)
  18. this.has[job.id] = job
  19. }
  20. }
  21. BatcherProto.flush = function () {
  22. // before flush hook
  23. if (this._preFlush) this._preFlush()
  24. // do not cache length because more jobs might be pushed
  25. // as we execute existing jobs
  26. for (var i = 0; i < this.queue.length; i++) {
  27. var job = this.queue[i]
  28. if (!job.cancelled) {
  29. job.execute()
  30. }
  31. }
  32. this.reset()
  33. }
  34. BatcherProto.reset = function () {
  35. this.has = utils.hash()
  36. this.queue = []
  37. this.waiting = false
  38. }
  39. module.exports = Batcher