Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function () {
- Polymer({
- is: 'fm-private-storex',
- properties: {
- /**
- * @description Store all states
- */
- store: {
- type: Object,
- value: function () {
- return {};
- }
- },
- /**
- * @description Array with callbacks functions subscribers
- */
- subscriptions: {
- type: Array,
- value: function () {
- return [];
- }
- },
- /**
- * @description Mutations saved to apply
- */
- mutations: {
- type: Object,
- value: function () {
- return [];
- },
- observer: 'onUpdateMutations'
- }
- },
- /**
- * @description Observers to apply changes on store
- */
- observers: ['onUpdate(store.*)'],
- /**
- * @description In attached generates all init object
- */
- attached: function () {
- /**
- * @description Object on window to get a bridge communication
- * @type {{subscribe, commit, mutations: *}}
- */
- window.gs = window.gs || {
- subscribe: this.subscribe.bind(this),
- commit: this.commit.bind(this),
- mutations: this.mutations
- }
- /**
- * @description Proxy to protect the bridge store
- * @type {Proxy}
- */
- var pgs = new Proxy(window.gs, {
- set: function (obj, prop, value) {
- if (prop === 'commit') {
- throw new TypeError('"commit" option cannot be modified');
- } else if (prop === 'mutations') {
- if (typeof value !== 'object') {
- throw new TypeError('"mutations" option should be an object');
- }
- } else if (prop === 'subscribe') {
- if (typeof value !== 'function') {
- throw new TypeError('"subscribe" option should be a function');
- }
- } else {
- throw new TypeError('The only valid options are "commit", "subscriptions" and "mutations"');
- }
- Reflect.set(obj, prop, value);
- },
- deleteProperty: function(target, prop) {
- throw new Error('This object cannot be deleted')
- }
- })
- window.gs = pgs;
- },
- /**
- * @description Function to subscribe the callbacks fn
- * @param fn
- * @returns {function(this:subscribe)}
- */
- subscribe: function (fn) {
- this.subscriptions.push(fn);
- return function () {
- var idx = this.subscriptions.indexOf(fn)
- if (idx > -1) {
- this.subscriptions.splice(idx, 1);
- }
- }.bind(this)
- },
- /**
- * @description Function to apply the mutations
- * @param mutation
- * @param value
- */
- commit: function (mutation, value) {
- this.set('mutations', gs.mutations);
- if (this.mutations[mutation]) {
- (this.mutations[mutation])(this, value);
- } else {
- throw new Error('The mutation ' + mutation + ' does not exist.');
- }
- },
- /**
- * @description Function that execute each fn from subscribers
- * @param store
- */
- onUpdate: function (store) {
- if (this.subscriptions) {
- this.subscriptions.forEach(function (t) {
- t(store);
- })
- }
- },
- onUpdateMutations: function (mutation) {
- console.log(mutation);
- }
- })
- })()
Add Comment
Please, Sign In to add comment