Skip to content

Instantly share code, notes, and snippets.

@uiur
Created June 6, 2014 01:54
Show Gist options
  • Save uiur/431e2283b625f4fbfc62 to your computer and use it in GitHub Desktop.
Save uiur/431e2283b625f4fbfc62 to your computer and use it in GitHub Desktop.
localStorageでブラウザの状態を同期するやつ
# localStorageで状態を保存・同期するやつ
#
# example:
# State.set('key', 'value')
# State.on('key', (changedValue) ->
# update(changedValue)
# )
angular.module('state')
.service 'State', [
'localStorageService'
'$interval'
(localStorageService, $interval) ->
Storage = localStorageService
class State extends EventEmitter2
constructor: ->
EventEmitter2.call(this)
@_watchStorage()
this
set: Storage.set.bind(Storage)
get: Storage.get.bind(Storage)
# @private
# pollingしてlocalStorageの値に変更があるか見る
_watchStorage: ->
@_takeSnapshot()
$interval(=>
Storage.keys().forEach((key) =>
currentValue = Storage.get(key)
unless currentValue == @snapshot[key]
@emit(key, currentValue)
)
@_takeSnapshot()
, 100)
_takeSnapshot: ->
@snapshot = @_fetchSnapshot()
_fetchSnapshot: ->
data = {}
Storage.keys().forEach((key) ->
data[key] = Storage.get(key)
)
data
new State()
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment