|
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 |
|
6 module.metadata = { |
|
7 "stability": "unstable" |
|
8 }; |
|
9 |
|
10 const { EventEmitter } = require('../deprecated/events'); |
|
11 const unload = require('../system/unload'); |
|
12 |
|
13 const Registry = EventEmitter.compose({ |
|
14 _registry: null, |
|
15 _constructor: null, |
|
16 constructor: function Registry(constructor) { |
|
17 this._registry = []; |
|
18 this._constructor = constructor; |
|
19 this.on('error', this._onError = this._onError.bind(this)); |
|
20 unload.ensure(this, "_destructor"); |
|
21 }, |
|
22 _destructor: function _destructor() { |
|
23 let _registry = this._registry.slice(0); |
|
24 for each (let instance in _registry) |
|
25 this._emit('remove', instance); |
|
26 this._registry.splice(0); |
|
27 }, |
|
28 _onError: function _onError(e) { |
|
29 if (!this._listeners('error').length) |
|
30 console.error(e); |
|
31 }, |
|
32 has: function has(instance) { |
|
33 let _registry = this._registry; |
|
34 return ( |
|
35 (0 <= _registry.indexOf(instance)) || |
|
36 (instance && instance._public && 0 <= _registry.indexOf(instance._public)) |
|
37 ); |
|
38 }, |
|
39 add: function add(instance) { |
|
40 let { _constructor, _registry } = this; |
|
41 if (!(instance instanceof _constructor)) |
|
42 instance = new _constructor(instance); |
|
43 if (0 > _registry.indexOf(instance)) { |
|
44 _registry.push(instance); |
|
45 this._emit('add', instance); |
|
46 } |
|
47 return instance; |
|
48 }, |
|
49 remove: function remove(instance) { |
|
50 let _registry = this._registry; |
|
51 let index = _registry.indexOf(instance) |
|
52 if (0 <= index) { |
|
53 this._emit('remove', instance); |
|
54 _registry.splice(index, 1); |
|
55 } |
|
56 } |
|
57 }); |
|
58 exports.Registry = Registry; |
|
59 |