Skip to content

Instantly share code, notes, and snippets.

Created November 30, 2014 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/86d8909abff4d5519593 to your computer and use it in GitHub Desktop.
Save anonymous/86d8909abff4d5519593 to your computer and use it in GitHub Desktop.
var Reflux = require('reflux'),
_ = require('underscore'),
api = require('./api');
var TodoActions = Reflux.createActions(['create', 'created', 'errored']);
TodoActions.create.preEmit = function(data) {
data = _.extend({_iid: _.uniqueId('todo_')}, data);
api.createTodo(data)
// API palauttaa saman objektin _iid kanssa
// turhaan sitä täällä tekee
.then(TodoActions.created)
.catch(TodoActions.errored)
return data;
}
module.exports = TodoActions;
var Reflux = require('reflux'),
_ = require('underscore'), // ei ehkä ole underscoressa deep clonea
TodoActions = require('./TodoActions');
module.exports = Reflux.createStore({
listenables: TodoActions,
state: {
todos: [],
},
findTodo(data) {
return _.find(this.state.todos, one => { return one.id ? one.id === data.id : one._iid === data._iid; });
},
onCreate(todo) {
this.saveState('todos');
this.state.todos.push(_.extend(todo));
this.trigger(this.state.todos);
},
// älä välitä mikä se oli, oletuksena niitä ei lisätä rinnakkain
onErrored() {
this.rollback('todos');
this.trigger(this.state.todos);
},
onCreated(todoData, id) {
var todo = todoData.data;
var existing = this.findTodo(todo);
if (!existing) return;
this.state.todos[this.state.todos.indexOf(existing)] = todo;
this.trigger(this.state.todos);
},
saveState(data) {
// tarvitsee lodashin
this.restore = _.clone(this.state, true);
},
rollback(data, key) {
if (key != undefined) {
this.state[key] = this.restore[key];
} else {
this.state = this.restore;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment