Add store to js runtime

This commit is contained in:
Lea Anthony
2020-08-30 15:49:12 +10:00
parent 9a7be38462
commit aa9cb5e58e
8 changed files with 2006 additions and 1389 deletions

View File

@@ -15,6 +15,7 @@ import { NewBinding } from './bindings';
import { Callback } from './calls';
import { AddScript, InjectCSS } from './utils';
import { AddIPCListener } from './ipc';
import * as Store from './store';
// Initialise global if not already
window.wails = window.wails || {};
@@ -42,6 +43,7 @@ var runtime = {
Heartbeat,
Acknowledge,
},
Store,
_: internal,
};

65
runtime/js/core/store.js Normal file
View File

@@ -0,0 +1,65 @@
/*
_ __ _ __
| | / /___ _(_) /____
| | /| / / __ `/ / / ___/
| |/ |/ / /_/ / / (__ )
|__/|__/\__,_/_/_/____/
The lightweight framework for web-like apps
(c) Lea Anthony 2019-present
*/
/* jshint esversion: 6 */
/**
* Creates a new sync store with the given name and optional default value
*
* @export
* @param {string} name
* @param {*} optionalDefault
*/
export function New(name, optionalDefault) {
var data;
if( !window.wails) {
throw Error('Wails is not initialised');
}
let callbacks = [];
this.subscribe = (callback) => {
callbacks.push(callback);
};
this.set = (newdata) => {
data = newdata;
// Emit the data
window.wails.Events.Emit('wails:sync:store:updated:'+name, data);
};
this.update = (updater) => {
var newValue = updater(data);
this.set(newValue);
};
// Setup event listener
window.wails.Events.On('wails:sync:store:updated:'+name, function(result) {
// Save data
data = result;
// Notify listeners
callbacks.forEach( function(callback) {
callback(data);
});
});
// Set to the optional default if set
if( optionalDefault ) {
this.set(optionalDefault);
}
return this;
}