Browse Source

Commit 3.1: replace fixture by MongoDB

Frederic G. MARAND 8 years ago
parent
commit
0b2faa29a1
2 changed files with 34 additions and 7 deletions
  1. 9 1
      simple-todos.html
  2. 25 6
      simple-todos.js

+ 9 - 1
simple-todos.html

@@ -1,21 +1,29 @@
+<!-- Predefined "head" template -->
 <head>
   <title>Todo List</title>
 </head>
 
+<!-- Predefined "body" template -->
 <body>
 <div class="container">
   <header>
     <h1>Todo List</h1>
+
+    <!-- add a form below the h1 -->
+    <form class="new-task">
+      <input type="text" name="text" placeholder="Type to add new tasks" />
+    </form>
   </header>
 
   <ul>
     {{#each tasks}}
-    {{> task}}
+      {{> task}}
     {{/each}}
   </ul>
 </div>
 </body>
 
+<!-- Custom "task" template -->
 <template name="task">
   <li>{{text}}</li>
 </template>

+ 25 - 6
simple-todos.js

@@ -1,10 +1,29 @@
+Tasks = new Mongo.Collection("tasks");
+
 if (Meteor.isClient) {
   // This code only runs on the client
   Template.body.helpers({
-    tasks: [
-      { text: "This is task 1" },
-      { text: "This is task 2" },
-      { text: "This is task 3" }
-    ]
+    tasks: function () {
+      return Tasks.find({}, { sort: {createdAt: -1 }});
+    }
   });
-}
+
+  // Inside the if (Meteor.isClient) block, right after Template.body.helpers:
+  Template.body.events({
+    "submit .new-task": function (event) {
+      // This function is called when the new task form is submitted
+
+      var text = event.target.text.value;
+
+      Tasks.insert({
+        text: text,
+        createdAt: new Date() // current time
+      });
+
+      // Clear form
+      event.target.text.value = "";
+
+      // Prevent default form submit
+      return false;
+    }
+  });}