vulcain-corejs
Version: 
Vulcain micro-service framework
78 lines (76 loc) • 2.9 kB
JavaScript
"use strict";
const dynamicProperties_1 = require("./dynamicProperties");
const rx = require("rx");
class ChainedDynamicProperty {
    constructor(manager, properties, defaultValue) {
        this.disposed = false;
        if (properties.length < 2)
            throw new Error("You must provided at least 2 properties.");
        this._propertyChanged = new rx.Subject();
        this._propertiesManager = manager;
        this._defaultValue = defaultValue;
        this._fallbackProperties = properties;
        // subscribe to changes
        this._reset = this.reset.bind(this);
        manager.propertyChanged.subscribe(this._reset);
        this.reset();
        dynamicProperties_1.DynamicProperties.registerPropertyAsDependency(this.name, defaultValue);
    }
    get propertyChanged() {
        return this._propertyChanged;
    }
    get name() {
        return this._fallbackProperties[0];
    }
    // One chained property has changed
    reset() {
        let old = this._activeProperty;
        let tmp;
        for (let propertyName of this._fallbackProperties) {
            tmp = this._propertiesManager.getProperty(propertyName);
            if (tmp) {
                break;
            }
        }
        this._activeProperty = tmp;
        if (old !== this._activeProperty) {
            this.onPropertyChanged();
        }
    }
    onPropertyChanged() {
        this._propertyChanged.onNext(this);
        this._propertiesManager.onPropertyChanged(this, "changed");
    }
    /// <summary>
    /// Current value
    /// </summary>
    get value() {
        if (this.disposed)
            throw new Error("Can not use a disposed property. Do you have call DynamicProperties.reset() ?");
        return this._activeProperty ? this._activeProperty.value : this._defaultValue;
    }
    /// <summary>
    /// Update default property value. This value can be overrided by a <see cref="IConfigurationSource"/>.
    /// Doesn't update source values.
    /// Assigning a value as precedence on all overriding properties
    /// Only the main property has precedence so others are ignored
    /// </summary>
    /// <param name="value">Property value</param>
    set(value) {
        if (this.disposed)
            throw new Error("Can not use a disposed property. Do you have call DynamicProperties.reset() ?");
        this._defaultValue = value;
        // Assigning a value as precedence on all overriding properties
        // Only the main property (the first) has precedence so ignore other one
        this._fallbackProperties = [this._fallbackProperties[0]];
        this.reset();
    }
    dispose() {
        this.disposed = true;
        this.onPropertyChanged();
        this._propertyChanged.dispose();
        this._propertyChanged = new rx.Subject();
    }
}
exports.ChainedDynamicProperty = ChainedDynamicProperty;
//# sourceMappingURL=chainedDynamicProperty.js.map