UNPKG

lpio

Version:

The last dashboard app you'll ever need

126 lines (106 loc) 3.95 kB
<link rel="import" href="../../bower_components/polymer/polymer.html"> <link rel="import" href="reducers/base-reducer.html"> <link rel="import" href="reducers/app-reducer.html"> <link rel="import" href="reducers/widget-reducer.html"> <link rel="import" href="reducers/dashboard-reducer.html"> <link rel="import" href="../settings/lp-settings.html"> <dom-module id="lp-redux"> <template></template> </dom-module> <script> /* The structure of the global state looks like DEFAULT_STATE below: app, widgets and dashboards are keys that can be observed and are modified by actions implemented by the app, widget and dashboard reducers. To call an action, execute the dispatch function on any lp-redux tag. Reducers are meant to be pure functions, that is, they should be *synchronous* and perform only computations, no side effects such as calling AJAX or things like : new Date() or Math.random(); */ (function () { var DEFAULT_STATE = { app: { currentDashboard: '', online: false, registeredWidgets:[], errors: [], warnings:[] }, widgets: { ids:[], isLoading: false, widgets:[], widgetsByDashboardId:{ // dashboardId: [... Array of widget Id's] } }, dashboards: { ids:[], isLoading: false, dashboards: [], dashboardsById:{ // id: {...} } } }; var instances = []; var globalState = _.extend({}, DEFAULT_STATE); Polymer({ is: 'lp-redux', properties: { state: { type: Object, notify: true, readonly: true }, reducers: { type: Array, readonly: true } }, behaviors:[ReduxBehaviors.Base,ReduxBehaviors.Widget,ReduxBehaviors.Dashboard,ReduxBehaviors.App], created: function () { instances.push(this); }, ready: function(){ this.state = globalState; // readOnly }, detached: function () { var i = instances.indexOf(this); if (i >= 0) { instances.splice(i, 1); } }, dispatch: function(action){ var self = this; var init = JSON.stringify(this.state); //this.push('history',action); // reducers modify and return the new state this.reducers.forEach(function(reducer){ if(typeof reducer == 'function'){ reducer.call(self,action); } }); console.log({action:JSON.stringify(action),stateStart:init,stateEnd:JSON.stringify(this.state)}); }, mutate: function(path,value){ var in_path = 'state.'+path; this.set(in_path,value); // we have a single object var me = instances.indexOf(this); //notify all other instances instances.forEach(function(instance,index){ if(index != me){ instance.notifyPath(in_path,value); } }); }, _addReducer: function(reducer){ if(typeof reducer == 'function'){ if(!_.isArray(this.reducers)){ this.reducers = []; } this.reducers.push(reducer); } } }); })(); </script>