cylon/lib/config.js

59 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2014-12-16 03:15:29 +08:00
"use strict";
var _ = require("./utils/helpers");
2014-11-07 01:48:21 +08:00
var config = module.exports = {},
callbacks = [];
// default data
2015-06-23 09:10:09 +08:00
config.haltTimeout = 3000;
config.testMode = false;
config.logger = null;
config.silent = false;
config.debug = false;
/**
* Updates the Config, and triggers handler callbacks
*
* @param {Object} data new configuration information to set
2015-06-23 09:10:09 +08:00
* @return {Object} the updated configuration
*/
config.update = function update(data) {
var forbidden = ["update", "subscribe", "unsubscribe"];
Object.keys(data).forEach(function(key) {
if (~forbidden.indexOf(key)) { delete data[key]; }
});
if (!Object.keys(data).length) {
2015-06-23 09:10:09 +08:00
return config;
}
_.extend(config, data);
callbacks.forEach(function(callback) { callback(data); });
2015-06-23 09:10:09 +08:00
return config;
};
/**
* Subscribes a function to be called whenever the config is updated
*
* @param {Function} callback function to be called with updated data
* @return {void}
*/
config.subscribe = function subscribe(callback) {
callbacks.push(callback);
};
/**
* Unsubscribes a callback from configuration changes
*
* @param {Function} callback function to unsubscribe from changes
* @return {void}
*/
config.unsubscribe = function unsubscribe(callback) {
var idx = callbacks.indexOf(callback);
if (idx >= 0) { callbacks.splice(idx, 1); }
};