simple-todos.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. Tasks = new Mongo.Collection("tasks");
  2. if (Meteor.isClient) {
  3. // This code only runs on the client
  4. Template.body.helpers({
  5. tasks: function () {
  6. if (Session.get('hideCompleted')) {
  7. return Tasks.find({ checked : { $ne : true }}, { sort: { createdAt: -1 }});
  8. } else {
  9. return Tasks.find({}, {sort: {createdAt: -1}});
  10. }
  11. },
  12. hideCompleted: function () {
  13. var ret = Session.get("hideCompleted");
  14. return ret;
  15. },
  16. incompleteCount: function () {
  17. var ret = Tasks.find({ checked: { $ne: true }}).count();
  18. return ret;
  19. }
  20. });
  21. // Inside the if (Meteor.isClient) block, right after Template.body.helpers:
  22. Template.body.events({
  23. "submit .new-task": function (event) {
  24. // This function is called when the new task form is submitted
  25. var text = event.target.text.value;
  26. // Insert a task into the collection.
  27. Meteor.call('addTask', text);
  28. // Clear form
  29. event.target.text.value = "";
  30. // Prevent default form submit
  31. return false;
  32. },
  33. 'change .hide-completed input': function (e) {
  34. Session.set('hideCompleted', e.target.checked);
  35. }
  36. });
  37. Template.task.events({
  38. 'click .delete': function (e) {
  39. Meteor.call('deleteTask', this._id);
  40. },
  41. 'click .toggle-checked' : function (e) {
  42. Meteor.call('setChecked', this._id, !this.checked);
  43. }
  44. });
  45. Accounts.ui.config({
  46. passwordSignupFields: "USERNAME_ONLY"
  47. });
  48. }
  49. Meteor.methods({
  50. addTask: function (text) {
  51. if (!Meteor.userId()) {
  52. throw new Meteor.Error('not-authorized');
  53. }
  54. var task = {
  55. text: text,
  56. createdAt: new Date(),
  57. owner: Meteor.userId(),
  58. username: Meteor.user().username
  59. };
  60. Tasks.insert(task);
  61. },
  62. deleteTask: function (taskId) {
  63. // Even not logged-in ?
  64. Tasks.remove(taskId);
  65. },
  66. setChecked: function (taskId, setChecked) {
  67. Tasks.update(taskId, { $set : { checked: setChecked }});
  68. }
  69. });