bigbluebutton-Github/bigbluebutton-html5/imports/ui/services/storage/reactive.js

81 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-03-10 03:50:21 +08:00
import _ from 'lodash';
2016-07-07 20:50:07 +08:00
import { Tracker } from 'meteor/tracker';
import { EJSON } from 'meteor/ejson';
// Reactive wrapper for browser Storage's
export default class StorageTracker {
constructor(storage, prefix = '') {
2017-06-03 03:25:02 +08:00
if (!(storage instanceof Storage)) {
2016-07-07 20:50:07 +08:00
throw `Expecting a instanceof Storage recieve a '${storage.constructor.name}' instance`;
}
this._trackers = {};
this._prefix = prefix;
this._storage = storage;
}
_ensureDeps(key) {
if (!this._trackers[key]) {
2017-06-03 03:25:02 +08:00
this._trackers[key] = new Tracker.Dependency();
2016-07-07 20:50:07 +08:00
}
}
_prefixedKey(key) {
2016-07-12 00:28:55 +08:00
key = key.replace(this._prefix, '');
2016-07-07 20:50:07 +08:00
return `${this._prefix}${key}`;
}
key(n) {
return this._storage.key(n);
}
getItem(key) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._ensureDeps(prefixedKey);
2016-07-12 03:42:54 +08:00
this._trackers[prefixedKey].depend();
2016-07-07 20:50:07 +08:00
2016-07-12 00:28:55 +08:00
let value = this._storage.getItem(prefixedKey);
2016-07-07 20:50:07 +08:00
if (value && _.isString(value)) {
try {
value = EJSON.parse(value);
} catch (e) {}
}
return value;
}
setItem(key, value) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._ensureDeps(prefixedKey);
2016-07-12 03:42:54 +08:00
// let currentValue = this.getItem(prefixedKey);
//
// if (_.isEqual(currentValue, value)) {
// return;
// }
2016-07-07 20:50:07 +08:00
if (_.isObject(value)) {
value = EJSON.stringify(value);
}
2016-07-12 00:28:55 +08:00
this._storage.setItem(prefixedKey, value);
this._trackers[prefixedKey].changed();
2016-07-07 20:50:07 +08:00
}
removeItem(key) {
2017-06-03 03:25:02 +08:00
const prefixedKey = this._prefixedKey(key);
2016-07-12 00:28:55 +08:00
this._storage.removeItem(prefixedKey);
if (!this._trackers[prefixedKey]) return;
2016-07-12 00:28:55 +08:00
this._trackers[prefixedKey].changed();
delete this._trackers[prefixedKey];
2016-07-07 20:50:07 +08:00
}
clear() {
2017-06-03 03:25:02 +08:00
Object.keys(this._trackers).forEach((key) => {
2016-07-07 20:50:07 +08:00
this.removeItem(key);
});
}
2017-06-03 03:25:02 +08:00
}