MeteorTips第二个应用程序教程 - 验证

时间:2015-11-12 17:41:17

标签: javascript meteor

我正在研究MeteorTips' Second tutorial的方法2章节,它基本上只是构建一个包含多个列表的待办事项应用程序。

我将用于将任务添加到列表中的代码移动到方法中,并决定尝试向任务添加一些验证,以使其不能为空且不能少于3个字符。我有验证工作,但我的代码在运行check(currentList,String)时返回Match failed错误。我可以看到它没有获取列表的ID,并且在变量中stroing undefined。

我的问题是,我该如何解决?

问题中的代码

HTML模板

<template name="addTodo">
  <form class="add-todo">
    Create a task
    <input type="text" placeholder="Type a task here..." name="todoName" />
  </form>
</template>

的JavaScript

if (Meteor.isClient){
...
  Template.addTodo.events({
    'submit form': function (event) {
      event.preventDefault();
    }
  });
...
  Template.addTodo.onRendered(function () {
    var validator = $('.add-todo').validate({
      submitHandler: function (event) {
        var todoName = $('[name="todoName"]').val();
        var currentList = this._id;
        console.log(todoName + " | " + currentList); // Assuming user inputs New Task, this returns New Task | undefined
        Meteor.call('createListItem', todoName, currentList, function (error, results) {
          if (error) {
            validator.showErrors({
              todoName: error.reason
            });
          } else {
            $('[name="todoName"]').val('');
          }
        });
      }
    });
  });
...
}

Meteor.methods({
...
  'createListItem': function (todoName, currentList) {
    check(todoName, String);
    check(currentList, String);
    var currentUser = Meteor.userId();
    var data = {
      name: todoName,
      completed: false,
      createdAt: new Date(),
      createdBy: currentUser,
      listId: currentList
    }
    if(!currentUser){
      throw new Meteor.Error("not-logged-in", "You're not logged in.");
    }
    return Todos.insert(data);
  },
});

如果您拥有Cloud 9帐户,则可以查看完整代码。服务器可能并不总是运行应用程序,因为我有一个免费帐户:

编辑(只读):https://ide.c9.io/blueknightone/meteor-todos

1 个答案:

答案 0 :(得分:0)

您需要保留对原始this的引用,因为您的submitHandler函数中的上下文正在发生变化。因此,您可以使用var self = this;,然后通过self.data访问模板的数据上下文:

Template.addTodo.onRendered(function() {
    var self = this;
    var validator = $('.add-todo').validate({
        submitHandler: function(event) {
            var todoName = $('[name="todoName"]').val();
            var currentList = self.data._id;
            console.log(todoName + " | " + currentList);
            Meteor.call('createListItem', todoName, currentList, function(error, results) {
                if (error) {
                    validator.showErrors({
                        todoName: error.reason
                    });
                } else {
                    $('[name="todoName"]').val('');
                }
            });
        }
    });
});

如果您想使用ES6 arrow functions,可以实施以下方法:

Template.addTodo.onRendered(function() {
    var validator = $('.add-todo').validate({
        submitHandler: (event) => {
            var todoName = $('[name="todoName"]').val();
            var currentList = this.data._id;
            console.log(todoName + " | " + currentList);
            Meteor.call('createListItem', todoName, currentList, function(error, results) {
                if (error) {
                    validator.showErrors({
                        todoName: error.reason
                    });
                } else {
                    $('[name="todoName"]').val('');
                }
            });
        }
    });
});