Created
March 15, 2017 11:59
-
-
Save mazikwyry/1f8aae65fef90bdd7a46595a362f5588 to your computer and use it in GitHub Desktop.
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
class ToDoStore | |
attr_reader :state | |
def initialize(initial_state = nil) | |
@state = initial_state | |
@listeners = [] | |
dispatch({}) | |
end | |
def dispatch(action) | |
@state = reducer(@state, action) | |
@listeners.each(&:call) | |
end | |
def subscribe(&listener) | |
@listeners << listener | |
-> { @listeners.delete(listener) } | |
end | |
def reducer(state, action) | |
case action[:type] | |
when :add_todo | |
state.push( | |
ToDo.new(action[:id], action[:body]) | |
) | |
else | |
state | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment