redux design models
import { PropTypes } from 'react'; | |
import { Record } from 'immutable'; | |
import { recordOf } from 'react-immutable-proptypes'; | |
const TaskRecord = new Record({ | |
id: undefined, | |
name: '', | |
deadline: undefined, | |
checked: false, | |
}); | |
export default class Task extends TaskRecord { | |
static PropTypes = recordOf({ | |
id: PropTypes.number, | |
name: PropTypes.string, | |
deadline: PropTypes.string, | |
checked: PropTypes.bool, | |
}) | |
setName(name) { | |
return this.set('name', name); | |
} | |
setDeadline(deadline) { | |
return this.set('deadline', deadline); | |
} | |
check() { | |
return this.set('checked', true); | |
} | |
revert() { | |
return this.set('checked', false); | |
} | |
isLate() { | |
return this.deadline < Date.now(); | |
} | |
submit() { | |
// FIXME http request | |
// とりあえずObjectをかえしておく | |
return this.toJS(); | |
} | |
} |
import { PropTypes } from 'react'; | |
import { Record, OrderedMap } from 'immutable'; | |
import { recordOf, mapOf, mapContains } from 'react-immutable-proptypes'; | |
import Task from './Task'; | |
const TodoStateRecord = new Record({ | |
tasks: new OrderedMap(), | |
inputTarget: undefined, | |
}); | |
export default class TodoState extends TodoStateRecord { | |
static PropTypes = recordOf({ | |
tasks: mapOf( | |
Task.PropTypes.isRequired, | |
mapContains(PropTypes.number.isRequired) | |
), | |
inputTarget: PropTypes.number, | |
}) | |
// actions | |
update({id, name, deadline}) { | |
return this.updateIn(['tasks', id], task => task.setName(name).setDeadline(deadline)); | |
} | |
create() { | |
const id = this.getLatestId() + 1; | |
return this.setIn(['tasks', id], new Task({ id })).changeInputTarget(id); | |
} | |
check(id) { | |
return this.updateIn(['tasks', id], task => task.check()); | |
} | |
submit() { | |
return this.changeInputTarget(undefined); | |
} | |
changeInputTarget(id) { | |
return this.set('inputTarget', id); | |
} | |
applyTaskResponse(object) { | |
return this.setIn(['tasks', object.id], new Task(object)); | |
} | |
// convenience methods | |
getLatestId() { | |
if (this.tasks.count() === 0) { | |
return 0; | |
} | |
return this.tasks.keySeq().max(); | |
} | |
getIncompleteTasks() { | |
return this.tasks.filter(task => !task.checked).valueSeq(); | |
} | |
getCompleteTasks() { | |
return this.tasks.filter(task => task.checked).valueSeq(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment