UNPKG

diffusion

Version:

Diffusion JavaScript client

59 lines (51 loc) 1.78 kB
var HashMap = require('hashmap'); /** * Mutable registry of service implementations, bound to a service definitions. */ function ServiceRegistry() { var services = new HashMap(); var listeners = []; /** * Retrieve a service for a specific definition. * * @param {ServiceDefinition} definition - The service definition. * @returns {Service|null} The service, if one exists, otherwise undefined. */ this.get = function(definition) { return services.get(definition); }; /** * Add a new service implementation to the registry. Only one service * may be bound to a given definition. * <P> * When a new service is added, any listeners will be notified. * * @param {ServiceDefinition} definition - The service definition * @param {Service} service - The service implementation * @throws Error if another service is already bound to the same definition. */ this.add = function(definition, service) { if (services.has(definition)) { throw new Error("Service already exists for " + definition); } services.set(definition, service); listeners.forEach(function(listener) { listener(definition, service); }); }; /** * Add a listener, to be notified whenever a new service implementation is added. *<P> * When a listener is added, it will immediately be called with all existing * services in the registry. * * @param {Function} listener - The registry listener. */ this.addListener = function(listener) { listeners.push(listener); services.forEach(function(k, v) { listener(v, k); }); }; } module.exports = ServiceRegistry;