Created
November 30, 2014 13:52
-
-
Save nnarhinen/d0f7fe9f6864853567a5 to your computer and use it in GitHub Desktop.
Reflux - handling ajax errors on creation
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
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; |
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
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