Skip to content

Instantly share code, notes, and snippets.

@funador
Last active January 21, 2019 04:46
Show Gist options
  • Save funador/492d4a53518fd658e01af7c24e9ec6f2 to your computer and use it in GitHub Desktop.
Save funador/492d4a53518fd658e01af7c24e9ec6f2 to your computer and use it in GitHub Desktop.
const handlers = (() => {
const _toast = message => {
Materialize.toast(message, 1500, 'rounded')
}
const _updateApi = (update, id) => {
api.updateTodo(update, id)
.then(updatedTodo => {
const originalTodo = store.findById(id)
const sameSame = updatedTodo.text === originalTodo.text
if (!sameSame) {
_toast('Todo Updated')
}
store.updateInStore(updatedTodo)
render.todos()
})
}
const addHandler = e => {
e.preventDefault()
const target = $(e.currentTarget).find('#todo')
const text = $target.val().trim()
target.val('')
if (!text) {
return _toast('Please add some text')
}
api.addTodo({text})
.then(newTodo => {
_toast('Todo Added')
store.addToStore(newTodo)
render.todos()
})
}
const deleteHandler = e => {
const id = $(e.currentTarget).closest('.collection-item').data('id')
api.deleteTodo(id)
.then(data => {
_toast('Todo Deleted')
store.deleteFromStore(data.id)
render.todos()
})
}
const editTextHandler = e => {
e.preventDefault()
const id = $(e.currentTarget).closest('.collection-item').data('id')
store.setEditing(id)
render.todos()
}
const updateTextHandler = e => {
e.preventDefault()
const $
target = $(e.currentTarget)
const $item = $target.closest('.collection-item')
const text = $item.find('input').val().trim()
const id = $item.data('id')
if (!text) {
return _toast('Please add some text')
}
store.setEditing(id)
_updateApi({text}, id)
}
const updateDoneHandler = e => {
const item = $(e.currentTarget).closest('.collection-item')
const id = item.data('id')
const done = item.find('.text').hasClass('completed')
? ''
: 'completed'
_updateApi({done}, id)
}
return {
addHandler,
deleteHandler,
editTextHandler,
updateTextHandler,
updateDoneHandler
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment