Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IBX-8445: Added storage class #1391

Open
wants to merge 1 commit into
base: 4.6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/bundle/Resources/encore/ibexa.js.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const layout = [
path.resolve(__dirname, '../public/js/scripts/core/toggle.button.js'),
path.resolve(__dirname, '../public/js/scripts/core/slug.value.input.autogenerator.js'),
path.resolve(__dirname, '../public/js/scripts/core/date.time.picker.js'),
path.resolve(__dirname, '../public/js/scripts/core/storage.js'),
path.resolve(__dirname, '../public/js/scripts/adaptive.filters.js'),
path.resolve(__dirname, '../public/js/scripts/admin.notifications.js'),
path.resolve(__dirname, '../public/js/scripts/button.trigger.js'),
Expand Down
57 changes: 57 additions & 0 deletions src/bundle/Resources/public/js/scripts/core/storage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
(function (global, doc, ibexa) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we don't need to pass window like global and window.document since I don't use them inside iife

class IbexaStorage {
constructor(config) {
const keySuffix = config.isUserAware ? `:${ibexa.helpers.user.getId()}` : '';

this.key = `${config.key}${keySuffix}`;
this.eventName = config.eventName;
}

stringfyData(data) {
try {
return JSON.stringify(data);
} catch (error) {
console.warn('Error stringifying data', error);
}
}

parseData(data) {
try {
return JSON.parse(data);
} catch (error) {
return null;
}
}

setItem(data) {
const stringifiedData = this.stringfyData(data);

window.localStorage.setItem(this.key, stringifiedData);

this.fireStorageChangeEvent(stringifiedData);
}

getItem() {
return this.parseData(window.localStorage.getItem(this.key));
}

fireStorageChangeEvent(data) {
if (this.eventName) {
const storageChangeEvent = new CustomEvent(this.eventName, {
cancelable: true,
detail: { content: this.parseData(data) },
});

document.body.dispatchEvent(storageChangeEvent);
}
}

init() {
if (this.eventName) {
window.addEventListener('storage', (event) => this.fireStorageChangeEvent(event.newValue));
}
}
}

ibexa.addConfig('core.Storage', IbexaStorage);
})(window, window.document, window.ibexa);
Loading