Created
July 30, 2015 06:35
-
-
Save turbobabr/9ace2c69673e65f3efcb to your computer and use it in GitHub Desktop.
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
import { createStore } from 'redux'; | |
import _ from 'underscore'; | |
const ADD_ITEM = 'ADD_ITEM'; | |
const REMOVE_ITEM = 'REMOVE_ITEM'; | |
const UPDATE_ITEM = 'UPDATE_ITEM'; | |
const initialState = { | |
items: [ | |
{ | |
id: 'item01', | |
name: "Jack" | |
}, | |
{ | |
id: 'item02', | |
name: "Howard" | |
} | |
] | |
}; | |
// Reducer | |
function itemsReducer(state = initialState, action = {}) { | |
switch(action.type) { | |
case ADD_ITEM: | |
return _.extend(state,{ | |
items: state.items.concat([action.item]) | |
}); | |
case REMOVE_ITEM: | |
return _.extend(state,{ | |
items: _.filter(state.items,(item) => item.id !== action.id) | |
}); | |
case UPDATE_ITEM: | |
return _.extend(state,{ | |
items: _.map(state.items,(item) => { | |
return item.id === action.id ? { ...item, name: action.name } : item; | |
}) | |
}); | |
default: | |
return state; | |
} | |
} | |
let store = createStore(itemsReducer); | |
store.subscribe(() => { | |
console.log(`Current state is: | |
------------------------------`); | |
_.each(store.getState().items,(item) => { | |
console.log(`${item.id}: ${item.name}`); | |
}); | |
console.log(`List contains ${store.getState().items.length} items | |
`); | |
}); | |
store.dispatch({ | |
type: ADD_ITEM, | |
item: { | |
id: 'item03', | |
name: "Ivan" | |
} | |
}); | |
store.dispatch({ | |
type: REMOVE_ITEM, | |
id: 'item02' | |
}); | |
store.dispatch({ | |
type: UPDATE_ITEM, | |
id: 'item03', | |
name: "Ivan IV (updated)" | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment