You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.3 KiB

4 years ago
  1. // This file should be ES5 compatible
  2. /* eslint prefer-spread:0, no-var:0, prefer-reflect:0, no-magic-numbers:0 */
  3. 'use strict'
  4. module.exports = (function () {
  5. // Import Events
  6. var events = require('events')
  7. // Export Domain
  8. var domain = {}
  9. domain.createDomain = domain.create = function () {
  10. var d = new events.EventEmitter()
  11. function emitError (e) {
  12. d.emit('error', e)
  13. }
  14. d.add = function (emitter) {
  15. emitter.on('error', emitError)
  16. }
  17. d.remove = function (emitter) {
  18. emitter.removeListener('error', emitError)
  19. }
  20. d.bind = function (fn) {
  21. return function () {
  22. var args = Array.prototype.slice.call(arguments)
  23. try {
  24. fn.apply(null, args)
  25. }
  26. catch (err) {
  27. emitError(err)
  28. }
  29. }
  30. }
  31. d.intercept = function (fn) {
  32. return function (err) {
  33. if ( err ) {
  34. emitError(err)
  35. }
  36. else {
  37. var args = Array.prototype.slice.call(arguments, 1)
  38. try {
  39. fn.apply(null, args)
  40. }
  41. catch (err) {
  42. emitError(err)
  43. }
  44. }
  45. }
  46. }
  47. d.run = function (fn) {
  48. try {
  49. fn()
  50. }
  51. catch (err) {
  52. emitError(err)
  53. }
  54. return this
  55. }
  56. d.dispose = function () {
  57. this.removeAllListeners()
  58. return this
  59. }
  60. d.enter = d.exit = function () {
  61. return this
  62. }
  63. return d
  64. }
  65. return domain
  66. }).call(this)