Skip to content

Instantly share code, notes, and snippets.

@nnarhinen
Created November 30, 2014 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nnarhinen/d0f7fe9f6864853567a5 to your computer and use it in GitHub Desktop.
Save nnarhinen/d0f7fe9f6864853567a5 to your computer and use it in GitHub Desktop.
Reflux - handling ajax errors on creation
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).then(function(todo) { TodoActions.created(_.extend({_iid: data._iid}, todo)); })
.catch(function(err) { TodoActions.errored(_.extend({_iid: data._iid}, {_error: err}))});
return data;
}
module.exports = TodoActions;
var Reflux = require('reflux'),
_ = require('underscore'),
TodoActions = require('./TodoActions');
module.exports = Reflux.createStore({
listenables: TodoActions,
todos: [],
findTodo: function(data) {
return _.find(this.todos, function(one) { return one.id ? one.id === data.id : one._iid === data._iid; });
}
onCreate: function(todo) {
this.todos.push(_.extend(todo, {_persisting: true}));
this.trigger(this.todos);
},
onErrored: function(todo) {
var existing = this.findTodo(todo);
if (!existing) return;
this.todos[this.todos.indexOf(existing)] = _.extend(_.omit(existing, '_persisting'), todo);
this.trigger(this.todos);
},
onCreated: function(todo) {
var existing = this.findTodo(todo);
if (!existing) return;
this.todos[this.todos.indexOf(existing)] = todo;
this.trigger(this.todos);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment