Created
August 11, 2014 16:00
-
-
Save evitolins/faf8acfc10110be9726b to your computer and use it in GitHub Desktop.
A simple class for manipulating key/value pairs, and applying associated callbacks.
This file contains 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
class DataModel | |
constructor: () -> | |
@data = {} | |
@callbacks = | |
set: [] | |
unset: [] | |
return | |
applyCallbacks: (action, args) -> | |
for cb in @callbacks[action] | |
cb.apply `undefined`, args if typeof cb is "function" | |
return | |
appendCallback: (action, callback) -> | |
@callbacks[action].push callback if @callbacks[action] isnt `undefined` | |
return | |
removeCallback: (action, callback) -> | |
for cb in @callbacks[action] | |
cb = @callbacks[action][i] | |
@callbacks[action].splice i, 1 if cb is callback | |
return | |
set: (key, value) -> | |
@data[key] = value | |
@applyCallbacks "set", [ | |
key | |
value | |
] | |
return | |
unset: (key) -> | |
if @data[key] isnt `undefined` | |
delete @data[key] | |
@applyCallbacks "unset", [key] | |
return | |
get: (key) -> | |
@data[key] | |
getAll: -> | |
@data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment