all files / src/ tasksj.js

100% Statements 32/32
100% Branches 6/6
100% Functions 10/10
100% Lines 32/32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82     18×                                                                                                
var jGetTasks = function() {
  jCallService({method: 'GET', url: '/tasks'}, jUpdateTasks);
}
 
var jCallService = function(options, callback) {
  $.ajax({
    type: options.method, 
    url: options.url,
    headers: {
      'Content-Type': options.contentType || 'text/plain'
    },
    data: options.data,
    dataType: 'text',
    contentType: options.contentType,
    success: function(data, status, xhr) {
      callback(200, data);
    },
    error: function(xhr, status, errorThrown) {
      callback(xhr.status, errorThrown);
    }
  });
}
 
var jUpdateTasks = function(status, response) {
  if(status === 200) {
    var tasks = $.parseJSON(response);
 
    $('#taskscount').html(tasks.length);
    
    var row = function(task) {
      return '<tr><td>' + task.name + '</td>' 
        + '<td>' + task.month + '/' + task.day + '/' +task.year + '</td>' 
        + '<td><A onclick="jDeleteTask(\'' + task._id + '\');">delete</A></td>'
        + '</tr>';
    }
    var table = '<table>' + tasks.map(row).join('') + '</table>';
    $('#tasks').html(table);
  } else {
      var message = response + ' (status: ' + status + ')';
//START:GETELEMENT    
      $('#message').html(message);
//END:GETELEMENT    
  }
}
 
var jInitpage = function() {
  jGetTasks();
  $('#submit').click(jAddTask);
}
 
var jAddTask = function() {
  var date = new Date($('#date').val());
  var newTask = { 
    name: $('#name').val(), 
    month: date.getMonth() + 1, 
    day: date.getDate(), 
    year: date.getFullYear()
  };
 
  if(validateTask(newTask)) {
    jCallService({method: 'POST', url: '/tasks', 
      contentType: 'application/json', 
      data: JSON.stringify(newTask)}, jUpdateMessage);    
  } else {
    jUpdateMessage(0, 'invalid task');
  }
    
  return false;
}
 
var jUpdateMessage = function(status, response) {
  $('#message').html(response + ' (status: ' + status + ')');
  jGetTasks();
}
 
var jDeleteTask = function(taskId) {
  jCallService({method: 'DELETE', url: '/tasks/' + taskId}, jUpdateMessage);
}
 
//START:READY
$(document).ready(jInitpage);
//END:READY