Skip to content

Commit

Permalink
Break api. Close #4
Browse files Browse the repository at this point in the history
  • Loading branch information
gosolivs committed May 11, 2019
1 parent b815bbc commit 8257012
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
33 changes: 17 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,37 @@ var parse = JSON.parse
* Storeon module to sync state at different tabs of the browser
* @param {Object} config The config object
* @param {String} [config.key = 'storeon-crosstab'] The default key
* @param {Boolean} [config.resetInit = false] Reset state at reloading tab
*/
var crossTab = function (config) {
config = config || {}

var key = config.key || 'storeon-crosstab'
var resetInit = config.resetInit || false
var sync = false

return function (store) {
store.on('crosstab', function (_, state) {
return state
})
store.on('@dispatch', function (_, e) {
if (e[0][0] === '@') {
if (e[0] === '@sync') sync = true
if (e[0] === '@changed') sync = false
return
}

if (!resetInit) {
try {
store.on('@init', function () {
return parse(localStorage.getItem(key))
})
} catch (e) {}
}
if (sync) return

store.on('@changed', function (state) {
try {
localStorage[key] = JSON.stringify(state)
} catch (e) {}
localStorage[key] = JSON.stringify({
name: e[0],
data: e[1],
time: +new Date()
})
} catch (er) {}
})

window.addEventListener('storage', function (e) {
if (e.key === key) {
store.dispatch('crosstab', parse(e.newValue))
var tip = parse(e.newValue)
store.dispatch('@sync')
store.dispatch(tip.name, tip.data)
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"size-limit": [
{
"path": "index.js",
"limit": "189 B"
"limit": "222 B"
}
],
"lint-staged": {
Expand Down

0 comments on commit 8257012

Please sign in to comment.