Created
June 6, 2014 01:54
-
-
Save uiur/431e2283b625f4fbfc62 to your computer and use it in GitHub Desktop.
localStorageでブラウザの状態を同期するやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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