registry.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { EventEmitter } = require('../deprecated/events');
  9. const unload = require('../system/unload');
  10. const Registry = EventEmitter.compose({
  11. _registry: null,
  12. _constructor: null,
  13. constructor: function Registry(constructor) {
  14. this._registry = [];
  15. this._constructor = constructor;
  16. this.on('error', this._onError = this._onError.bind(this));
  17. unload.ensure(this, "_destructor");
  18. },
  19. _destructor: function _destructor() {
  20. let _registry = this._registry.slice(0);
  21. for each (let instance in _registry)
  22. this._emit('remove', instance);
  23. this._registry.splice(0);
  24. },
  25. _onError: function _onError(e) {
  26. if (!this._listeners('error').length)
  27. console.error(e);
  28. },
  29. has: function has(instance) {
  30. let _registry = this._registry;
  31. return (
  32. (0 <= _registry.indexOf(instance)) ||
  33. (instance && instance._public && 0 <= _registry.indexOf(instance._public))
  34. );
  35. },
  36. add: function add(instance) {
  37. let { _constructor, _registry } = this;
  38. if (!(instance instanceof _constructor))
  39. instance = new _constructor(instance);
  40. if (0 > _registry.indexOf(instance)) {
  41. _registry.push(instance);
  42. this._emit('add', instance);
  43. }
  44. return instance;
  45. },
  46. remove: function remove(instance) {
  47. let _registry = this._registry;
  48. let index = _registry.indexOf(instance)
  49. if (0 <= index) {
  50. this._emit('remove', instance);
  51. _registry.splice(index, 1);
  52. }
  53. }
  54. });
  55. exports.Registry = Registry;