simple-todos.js 2.5 KB

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