Skip to content

Instantly share code, notes, and snippets.

@Cologler
Last active January 15, 2018 15:08
Show Gist options
  • Save Cologler/4d17f402d126b9c1bf3d6363d1a415a9 to your computer and use it in GitHub Desktop.
Save Cologler/4d17f402d126b9c1bf3d6363d1a415a9 to your computer and use it in GitHub Desktop.
SingletonData allow read write single data on mulit-tabs.
// ==UserScript==
// @name SingletonData
// @namespace https://github.com/cologler/
// @version 0.3
// @description try to take over the world!
// @author cologler
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addValueChangeListener
// @grant GM_removeValueChangeListener
// ==/UserScript==
// just let type script work.
(function() { function require(){}; require("greasemonkey"); })();
let SingletonData = (() => {
let names = new Set();
class SingletonData {
constructor(key, defaultValue = null) {
if (typeof key !== 'string') throw 'key must be string';
if (!key) throw 'key cannot be empty';
if (names.has(key)) throw `SingletonData <${key}> is created.`;
names.add(key);
const unset = {};
let data = unset;
let isDisposed = false;
function ensureSafe() {
if (isDisposed) throw 'object is disposed.';
}
Object.defineProperty(this, 'data', {
get: () => {
ensureSafe();
if (data === unset) {
data = GM_getValue(key, defaultValue);
}
return data;
},
set: value => {
ensureSafe();
data = value;
GM_setValue(key, value);
}
});
this.save = () => {
ensureSafe();
GM_setValue(key, data);
};
const listenerId = GM_addValueChangeListener(key, (_, oldValue, newValue, remote) => {
if (!remote) return;
data = newValue;
});
this.dispose = () => {
isDisposed = true;
GM_removeValueChangeListener(listenerId);
names.delete(key);
};
}
}
return SingletonData;
})();

Singleton data on mulit-tabs.

// create instance
let sd = new SingletonData(key, defaultValue = null);
// set root value and it auto save.
sd.data = 1;

// set second level value and you need to call save()
sd.data.data2 = 1;
sd.save();

// dispose if you not need it any more.
sd.dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment