Skip to content

Instantly share code, notes, and snippets.

@mathildathompson
Created April 8, 2014 23:55
Show Gist options
  • Save mathildathompson/10210622 to your computer and use it in GitHub Desktop.
Save mathildathompson/10210622 to your computer and use it in GitHub Desktop.
$(document).ready(function () {
//Change underscore template settings;
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
jsTodoApp.showTasks();
$('#tasks').on('click', '.task .task-status', function () {
var $task = $(this).closest('.task');
var taskID = $task.attr('data-taskID');
// var task = jsTodoApp.tasks[taskID]; //This will be its index position in the array;
// console.log(task);
// task.completedAt = (new Date()).toString();
var task = jsTodoApp.updateTask(taskID, true);
});
$('#completed').on('click', '.task .task-status', function () {
var $task = $(this).closest('.task');
var taskID = $task.attr('data-taskID');
// var task = jsTodoApp.tasks[taskID];
// task.completedAt = null;
var task = jsTodoApp.updateTask(taskID, false);
});
$('#container').on('click', '.delete-task', function(){
var $task = $(this).closest('div');
var taskID = $task.data('task-id');
$task.fadeOut(function(){
jsTodoApp.deleteTask(taskID);
})
})
$('form.task_creator').on('submit', function (event) {
event.preventDefault();
var $input = $('#new_task');
var description = $input.val();
$input.val('');
jsTodoApp.createTask(description);
jsTodoApp.showTasks();
});
});
var jsTodoApp = {
createTask: function (description) {
$.ajax({
url: '/tasks',
type: 'POST',
dataType: 'json',
data: {task: {description: description, completed: false}}
}).done(function(data){
console.log(data);
})
},
showTasks: function () {
$('.task').remove(); //What is this line doing?
var task_format = $('#task_template').html();
var task_html = _.template(task_format);
$.ajax({
url: '/tasks',
dataType: 'json',
type: 'GET'
}).done(function(tasks){
_.each(tasks, function (task) {
var html = task_html(task);
if (task.completed) {
$(html).appendTo('#completed');
} else {
$(html).appendTo('#tasks');
}
});
})
},
updateTask: function(taskID, completed){
$.ajax({
url: '/update',
dataType: 'json',
type: 'POST',
data: {id: taskID, completed: completed}
}).done(function(task){
var task_format = $('#task_template').html();
var task_html = _.template(task_format);
var $task = $('.task[data-taskID="' + task.id + '"]');
$task.fadeOut(function () {
$task.remove();
$task = $(task_html(task));
if (task.completed) {
$task.prependTo('#completed');
} else {
$task.prependTo('#tasks');
}
});
})
},
deleteTask: function(task){
$.ajax({
url: '/destroy',
dataType: 'json',
action: 'delete',
data: {id: task}
}).done(function(){
console.log('Task deleted');
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment