// Subscribing to the published tasks
Meteor.subscribe("tasks");
// Show/Hide functionality
Template.body.helpers({
tasks: function () {
if (Session.get("hideCompleted")) {
// If hide completed is checked, filter tasks
return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
} else {
// Otherwise, return all of the tasks
return Tasks.find({}, {sort: {createdAt: -1}});
}
},
hideCompleted: function () {
return Session.get("hideCompleted");
},
incompleteCount: function () {
return Tasks.find({checked: {$ne: true}}).count();
}
});
// Events for creating new tasks and Show/Hide functionality.
// Calling methods from the server
Template.body.events({
"submit .new-task": function (event) {
event.preventDefault();
var text = event.target.text.value;
Meteor.call("addTask", text);
event.target.text.value = "";
},
"change .hide-completed input": function (event) {
Session.set("hideCompleted", event.target.checked);
}
});
// Events for Deleting and Check/Uncheck functionality
Template.Task.events({
"click .toggle-checked": function () {
// Set the checked property to the opposite of its current value
Meteor.call("setChecked", this._id, ! this.checked);
},
"click .delete": function () {
Meteor.call("deleteTask", this._id);
}
});
Листинг client/main.html
<head>
<title>Todo App</title>
</head>
<body>
<h1>Todo List ({{incompleteCount}})</h1>
<label class = "hide-completed">
<input type = "checkbox" checked = "{{hideCompleted}}" />
Hide Completed Tasks
</label>
<form class = "new-task">
<input type = "text" name = "text" placeholder = "Add new tasks" />
</form>
<ul>
{{#each tasks}}
{{> task}}
{{/each}}
</ul>
</body>
<template name = "task">
<li class = "{{#if checked}}checked{{/if}}">
<button class = "delete">x</button>
<input type = "checkbox" checked = "{{checked}}" class = "toggle-checked" />
<span>{{username}} - {{text}}</span>
</li>
</template>
Листинг server/main.js
// Publishing tasks from the server...
Meteor.publish("tasks", function () {
return Tasks.find({});
});
// Methods for handling MongoDb Tasks collection data...
Meteor.methods({
addTask: function (text) {
Tasks.insert({
text: text,
createdAt: new Date(),
});
},
deleteTask: function (taskId) {
var task = Tasks.findOne(taskId);
Tasks.remove(taskId);
},
setChecked: function (taskId, setChecked) {
var task = Tasks.findOne(taskId);
Tasks.update(taskId, { $set: { checked: setChecked} });
}
});