From 34650a216c4b72fa4048ec74a41081f4eec5b4ed Mon Sep 17 00:00:00 2001 From: Federico Brigante Date: Wed, 31 Jul 2019 22:01:45 +0700 Subject: [PATCH] Add `stopFormSync` It will enable https://github.com/sindresorhus/refined-github/issues/1714#issuecomment-501079632 --- index.ts | 38 ++++++++++++++++++++++++++++---------- readme.md | 4 ++++ 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/index.ts b/index.ts index 8c1daf9..91362bc 100644 --- a/index.ts +++ b/index.ts @@ -73,6 +73,7 @@ class OptionsSync { }: Setup = {}) { this.storageName = storageName; this.defaults = defaults; + this._handleFormInput = debounce(600, this._handleFormInput.bind(this)); if (logging === false) { this._log = () => {}; @@ -169,20 +170,27 @@ class OptionsSync { form : document.querySelector(form)!; - element.addEventListener('input', debounce(600, this._handleFormInput.bind(this))); - chrome.storage.onChanged.addListener((changes, namespace) => { - if ( - namespace === 'sync' && - changes[this.storageName] && - !element.contains(document.activeElement) // Avoid applying changes while the user is editing a field - ) { - deserialize(element, changes[this.storageName].newValue); - } - }); + element.addEventListener('input', this._handleFormInput); + chrome.storage.onChanged.addListener(this._handleStorageChangeOnForm.bind(this, element)); deserialize(element, await this.getAll()); } + /** + Removes any listeners added by `syncForm` + + @param selector - The `
` that needs to be unsynchronized or a CSS selector (one element). + The form fields' `name` attributes will have to match the option names. + */ + async stopSyncForm(form: string | HTMLFormElement): Promise { + const element = form instanceof HTMLFormElement ? + form : + document.querySelector(form)!; + + element.removeEventListener('input', this._handleFormInput); + chrome.storage.onChanged.removeListener(this._handleStorageChangeOnForm.bind(this, element)); + } + private _log(method: keyof Console, ...args: any[]): void { console[method](...args); } @@ -214,6 +222,16 @@ class OptionsSync { bubbles: true })); } + + private _handleStorageChangeOnForm(form: HTMLFormElement, changes: Record, areaName: string): void { + if ( + areaName === 'sync' && + changes[this.storageName] && + !form.contains(document.activeElement) // Avoid applying changes while the user is editing a field + ) { + deserialize(form, changes[this.storageName].newValue); + } + } } export default OptionsSync; diff --git a/readme.md b/readme.md index 4904a58..f9010e9 100644 --- a/readme.md +++ b/readme.md @@ -270,6 +270,10 @@ Type: `HTMLFormElement`, `string` It's the `` that needs to be synchronized or a CSS selector (one element). The form fields' `name` attributes will have to match the option names. +#### opts.stopSyncForm(form) + +Removes any listeners added by `syncForm`. + ## Related * [webext-storage-cache](https://github.com/fregante/webext-storage-cache) - Map-like promised cache storage with expiration.