aboutsummaryrefslogtreecommitdiff
path: root/tools/addon-sdk-1.5/packages/api-utils/lib/utils/registry.js
blob: 2ce6a6e90292741293a5959f0c3e333725bfeb98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const { EventEmitter } = require('../events');
const unload = require('../unload');

const Registry = EventEmitter.compose({
  _registry: null,
  _constructor: null,
  constructor: function Registry(constructor) {
    this._registry = [];
    this._constructor = constructor;
    this.on('error', this._onError = this._onError.bind(this));
    unload.ensure(this, "_destructor");
  },
  _destructor: function _destructor() {
    let _registry = this._registry.slice(0);
    for each (let instance in _registry)
      this._emit('remove', instance);
    this._registry.splice(0);
  },
  _onError: function _onError(e) {
    if (!this._listeners('error').length)
      console.error(e);
  },
  has: function has(instance) {
    let _registry = this._registry;
    return (
      (0 <= _registry.indexOf(instance)) ||
      (instance && instance._public && 0 <= _registry.indexOf(instance._public))
    );
  },
  add: function add(instance) {
    let { _constructor, _registry } = this; 
    if (!(instance instanceof _constructor))
      instance = new _constructor(instance);
    if (0 > _registry.indexOf(instance)) {
      _registry.push(instance);
      this._emit('add', instance);
    }
    return instance;
  },
  remove: function remove(instance) {
    let _registry = this._registry;
    let index = _registry.indexOf(instance)
    if (0 <= index) {
      this._emit('remove', instance);
      _registry.splice(index, 1);
    }
  }
});
exports.Registry = Registry;