michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: "use strict"; michael@0: michael@0: module.metadata = { michael@0: "stability": "unstable" michael@0: }; michael@0: michael@0: const { EventEmitter } = require('../deprecated/events'); michael@0: const unload = require('../system/unload'); michael@0: michael@0: const Registry = EventEmitter.compose({ michael@0: _registry: null, michael@0: _constructor: null, michael@0: constructor: function Registry(constructor) { michael@0: this._registry = []; michael@0: this._constructor = constructor; michael@0: this.on('error', this._onError = this._onError.bind(this)); michael@0: unload.ensure(this, "_destructor"); michael@0: }, michael@0: _destructor: function _destructor() { michael@0: let _registry = this._registry.slice(0); michael@0: for each (let instance in _registry) michael@0: this._emit('remove', instance); michael@0: this._registry.splice(0); michael@0: }, michael@0: _onError: function _onError(e) { michael@0: if (!this._listeners('error').length) michael@0: console.error(e); michael@0: }, michael@0: has: function has(instance) { michael@0: let _registry = this._registry; michael@0: return ( michael@0: (0 <= _registry.indexOf(instance)) || michael@0: (instance && instance._public && 0 <= _registry.indexOf(instance._public)) michael@0: ); michael@0: }, michael@0: add: function add(instance) { michael@0: let { _constructor, _registry } = this; michael@0: if (!(instance instanceof _constructor)) michael@0: instance = new _constructor(instance); michael@0: if (0 > _registry.indexOf(instance)) { michael@0: _registry.push(instance); michael@0: this._emit('add', instance); michael@0: } michael@0: return instance; michael@0: }, michael@0: remove: function remove(instance) { michael@0: let _registry = this._registry; michael@0: let index = _registry.indexOf(instance) michael@0: if (0 <= index) { michael@0: this._emit('remove', instance); michael@0: _registry.splice(index, 1); michael@0: } michael@0: } michael@0: }); michael@0: exports.Registry = Registry; michael@0: