Meteorjs:无法隐藏UI元素

时间:2016-02-26 17:48:15

标签: javascript node.js meteor

我正在关注教程here,该教程是关于在meteorjs中设置会话变量的。

但我无法让这个例子起作用。单击隐藏按钮不会执行任何操作。

JS:

Tasks = new Mongo.Collection("tasks");
if (Meteor.isClient) {
  // This code only runs on the client
  Template.body.helpers({
    tasks: function(){
    console.log("function called");
      if (Session.get("hideCompleted")) {
        // If hide completed is checked, filter tasks
        console.log("success!");

        return Tasks.find({checked: {$ne: true}}, {sort: {createdAt: -1}});
      } else {
        console.log("failure!");
        // Otherwise, return all of the tasks
        return Tasks.find({}, {sort: {createdAt: -1}});
      }
    },
    hideCompleted: function () {
      return Session.get("hideCompleted");     }
  });
  Template.body.events({
    "submit .new-task": function (event) {
      // Prevent default browser form submit
      event.preventDefault();
      // Get value from form element
      var text = event.target.text.value;
      // Insert a task into the collection
      Tasks.insert({
        text: text,
        createdAt: new Date() // current time
      });
      // Clear form
      event.target.text.value = "";
    }
  });
  Template.task.events({
    "click .toggle-checked": function () {
      // Set the checked property to the opposite of its current value
      Tasks.update(this._id, {
        $set: {checked: ! this.checked}
      });
    },
    "click .delete": function () {
      Tasks.remove(this._id);
    },
    "change .hide-completed input": function (event) {
      console.log("Changed!");
      Session.set("hideCompleted", event.target.checked);

    }
  });
}

HTML:

<head>
  <title>Todo List</title>
</head>
<body>
  <div class="container">
    <header>
      <h1>Todo List </h1>
        <label class="hide-completed">
        <input type="checkbox" checked="{{hideCompleted}}" />
          Hide Completed Tasks
        </label>
        <form class="new-task">
        <h2> Add a task </h2>
          <input type="text" name="text" placeholder="Type to add new tasks" />
        </form>
    </header>
    <ul>
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </ul>
  </div>
</body>
<template name="task">
  <li class="{{#if checked}}checked{{/if}}">
    <button class="delete">&times;</button>
    <input type="checkbox" checked="{{checked}}" class="toggle-checked" />
    <span class="text">{{text}}</span>
  </li>
</template>

开始时我的控制台输出符合预期:

function called
failure!

但是单击hide-completed复选框时,不会触发任何事件(即控制台日志不会更改)。我错过了什么?

1 个答案:

答案 0 :(得分:1)

我想说这可能是因为你定义了你的&#34;切换检查&#34;在Template.task.events中的处理程序,确实你的复选框不是&#34;任务&#34;模板。 将处理程序放在body事件中,应该正确调用它。