react-native/Libraries/Settings/Settings.ios.js

76 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-05-05 12:34:38 +00:00
/**
* Copyright (c) Facebook, Inc. and its affiliates.
2015-05-05 12:34:38 +00:00
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
2015-05-05 12:34:38 +00:00
*
* @format
2015-05-05 12:34:38 +00:00
* @flow
*/
2015-05-05 12:34:38 +00:00
'use strict';
const RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
const RCTSettingsManager = require('NativeModules').SettingsManager;
2015-05-05 12:34:38 +00:00
const invariant = require('fbjs/lib/invariant');
2015-05-05 12:34:38 +00:00
const subscriptions: Array<{keys: Array<string>, callback: ?Function}> = [];
2015-05-05 12:34:38 +00:00
const Settings = {
_settings: RCTSettingsManager && RCTSettingsManager.settings,
2015-05-05 12:34:38 +00:00
get(key: string): mixed {
return this._settings[key];
},
set(settings: Object) {
this._settings = Object.assign(this._settings, settings);
RCTSettingsManager.setValues(settings);
2015-05-05 12:34:38 +00:00
},
watchKeys(keys: string | Array<string>, callback: Function): number {
if (typeof keys === 'string') {
2015-05-05 12:34:38 +00:00
keys = [keys];
}
invariant(
Array.isArray(keys),
'keys should be a string or array of strings',
2015-05-05 12:34:38 +00:00
);
const sid = subscriptions.length;
subscriptions.push({keys: keys, callback: callback});
2015-05-05 12:34:38 +00:00
return sid;
},
clearWatch(watchId: number) {
if (watchId < subscriptions.length) {
subscriptions[watchId] = {keys: [], callback: null};
}
},
_sendObservations(body: Object) {
Object.keys(body).forEach(key => {
const newValue = body[key];
const didChange = this._settings[key] !== newValue;
this._settings[key] = newValue;
2015-05-05 12:34:38 +00:00
if (didChange) {
subscriptions.forEach(sub => {
if (sub.keys.indexOf(key) !== -1 && sub.callback) {
2015-05-05 12:34:38 +00:00
sub.callback();
}
});
}
});
},
};
RCTDeviceEventEmitter.addListener(
'settingsUpdated',
Settings._sendObservations.bind(Settings),
2015-05-05 12:34:38 +00:00
);
module.exports = Settings;