addon-sdk/source/lib/sdk/util/registry.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/util/registry.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,59 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +"use strict";
     1.8 +
     1.9 +module.metadata = {
    1.10 +  "stability": "unstable"
    1.11 +};
    1.12 +
    1.13 +const { EventEmitter } = require('../deprecated/events');
    1.14 +const unload = require('../system/unload');
    1.15 +
    1.16 +const Registry = EventEmitter.compose({
    1.17 +  _registry: null,
    1.18 +  _constructor: null,
    1.19 +  constructor: function Registry(constructor) {
    1.20 +    this._registry = [];
    1.21 +    this._constructor = constructor;
    1.22 +    this.on('error', this._onError = this._onError.bind(this));
    1.23 +    unload.ensure(this, "_destructor");
    1.24 +  },
    1.25 +  _destructor: function _destructor() {
    1.26 +    let _registry = this._registry.slice(0);
    1.27 +    for each (let instance in _registry)
    1.28 +      this._emit('remove', instance);
    1.29 +    this._registry.splice(0);
    1.30 +  },
    1.31 +  _onError: function _onError(e) {
    1.32 +    if (!this._listeners('error').length)
    1.33 +      console.error(e);
    1.34 +  },
    1.35 +  has: function has(instance) {
    1.36 +    let _registry = this._registry;
    1.37 +    return (
    1.38 +      (0 <= _registry.indexOf(instance)) ||
    1.39 +      (instance && instance._public && 0 <= _registry.indexOf(instance._public))
    1.40 +    );
    1.41 +  },
    1.42 +  add: function add(instance) {
    1.43 +    let { _constructor, _registry } = this; 
    1.44 +    if (!(instance instanceof _constructor))
    1.45 +      instance = new _constructor(instance);
    1.46 +    if (0 > _registry.indexOf(instance)) {
    1.47 +      _registry.push(instance);
    1.48 +      this._emit('add', instance);
    1.49 +    }
    1.50 +    return instance;
    1.51 +  },
    1.52 +  remove: function remove(instance) {
    1.53 +    let _registry = this._registry;
    1.54 +    let index = _registry.indexOf(instance)
    1.55 +    if (0 <= index) {
    1.56 +      this._emit('remove', instance);
    1.57 +      _registry.splice(index, 1);
    1.58 +    }
    1.59 +  }
    1.60 +});
    1.61 +exports.Registry = Registry;
    1.62 +

mercurial