Skip to content

Instantly share code, notes, and snippets.

@mockdeep
Last active August 29, 2015 14:17
Show Gist options
  • Save mockdeep/f6d62d6ad9d2065ec6ee to your computer and use it in GitHub Desktop.
Save mockdeep/f6d62d6ad9d2065ec6ee to your computer and use it in GitHub Desktop.
javascript todo list app, ugly code
(function () {
'use strict';
var itemTemplate = $('#templates .item');
var list = $('#list');
// when I load the page, I want to get the tasks from the API
$.ajax({
type: 'GET',
url: "https://listalous.herokuapp.com/lists/lobatis-list",
}).done(function(list) {
list.items.forEach(addItemToPage);
});
// this gets the form out of the page
var form = $('#add-form');
// when I add a task, it should add it to the list
var addItemToPage = function(itemData) {
var item = itemTemplate.clone()
item.attr('data-id', itemData.id)
item.find('.description').text(itemData.description)
if(itemData.completed) {
item.addClass('completed')
}
list.append(item)
setClickCallbacks(item)
}
var preventStuff = function (event) {
event.preventDefault();
var input = $(this).find('input')
var title = input.val();
input.val('');
var itemData = { description: title, completed: false };
$.ajax({
type: 'POST',
url: "https://listalous.herokuapp.com/lists/lobatis-list/items",
data: itemData,
success: function(data) {
addItemToPage(data);
},
error: function() {
alert('there was an error');
}
})
};
form.on('submit', preventStuff);
// when I click the checkmark, it should mark the task done
// when they click on the mark
function setClickCallbacks(item) {
var id = item.attr('data-id');
var itemUrl = 'https://listalous.herokuapp.com/lists/lobatis-list/items/' + id;
item.find('.description').on('click', function() {
var description = $(this);
description.hide();
var input = $('<input value="' + $(this).text() + '"></input>')
item.append(input)
input.on('keydown', function (event) {
if (event.keyCode === 13) {
$.ajax({
type: 'PUT',
url: itemUrl,
data: { description: input.val() }
}).done(function () {
description.text(input.val());
input.remove();
description.show();
});
}
})
})
item.find('.complete-button').on('click', function() {
// get item id
// make our ajax request
$.ajax({
type: 'PUT',
url: itemUrl,
data: { completed: !item.completed }
}).done(function () {
item.toggleClass('completed');
});
});
item.find('.delete-button').on('click', function () {
$.ajax({
type: 'DELETE',
url: itemUrl
}).done(function () {
item.remove();
});
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment