Skip to content

Instantly share code, notes, and snippets.

@tatat
Last active April 10, 2017 19:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tatat/5cc7f61a20b453db1057561b57f80ea2 to your computer and use it in GitHub Desktop.
Vuex on Electron
import { ipcMain, BrowserWindow } from 'electron'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count: 0
}
const mutations = {
increment(state, { amount }) {
state.count += amount
}
}
const actions = {
incrementAsync({ commit }, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('increment', payload)
resolve()
}, 0)
})
}
}
const getters = {
}
const broadcastPlugin = store => {
store.subscribe((mutation, state) => {
BrowserWindow.getAllWindows().forEach(window => {
window.webContents.send('store:state', state)
})
})
}
export const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [broadcastPlugin]
})
ipcMain.on('store:sync', event => {
event.returnValue = store.state
})
ipcMain.on('store:commit', (event, type, payload) => {
store.commit(type, payload)
})
ipcMain.on('store:dispatch', (event, id, type, payload) => {
Promise.resolve(store.dispatch(type, payload)).then(returnValue => {
event.sender.send(`store:dispatch:${id}`, null, returnValue)
}, error => {
event.sender.send(`store:dispatch:${id}`, error.toString()) // うーん...
})
})
ipcMain.on('store:get', (event, type, payload) => {
let value = store.getters[type]
if (typeof value === 'function') {
value = {callable: true}
} else {
value = {callable: false, value}
}
event.returnValue = value
})
ipcMain.on('store:getter', (event, type, payload) => {
event.returnValue = store.getters[type](payload)
})
import { ipcRenderer } from 'electron'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store()
ipcRenderer.on('store:state', (event, mainState) => {
store.replaceState(mainState)
})
store.replaceState(ipcRenderer.sendSync('store:sync'))
export const commit = (type, payload) => {
ipcRenderer.send('store:commit', type, payload)
}
let currentId = 0
const generateId = () => `${process.pid}-${currentId ++}`
export const dispatch = (type, payload) => {
const id = generateId()
return new Promise((resolve, reject) => {
ipcRenderer.once(`store:dispatch:${id}`, (event, errorMessage, returnValue) => {
if (errorMessage) {
reject(new Error(errorMessage)) // うーん...
} else {
resolve(returnValue)
}
})
ipcRenderer.send('store:dispatch', id, type, payload)
})
}
// can not be reactive ...
export const getters = new Proxy({}, {
get(target, name) {
const id = generateId()
const params = ipcRenderer.sendSync('store:get', name)
if (params.callable) {
return payload => ipcRenderer.sendSync('store:getter', name, payload)
} else {
return params.value
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment