Meteor不在网页中添加和显示任务,只是闪烁和故障(创建Todos列表以添加和删除任务)

时间:2018-05-19 04:28:40

标签: meteor

// client \ main.js中的客户端代码

任务=新的Mongo.Collection('任务');

Template.tasks.helpers({
    tasks:function () {
        return Tasks.find({},{sort:{createdAt:-1}});
    }
});

Template.tasks.events({
    "submit .add-task":function (event) {
        var name = event.target.name.value;

        Meteor.call('addTask',name);
        event.target.name.value='';

        return false;
    },
    "click .delete-task":function (event) {
        if(confirm('Delete Task?')){
            Meteor.call('deleteTask',this._id);
        }
        return false;
    }
});

Meteor.methods({
    addTask: function (name) {
        if (!Meteor.userId()) {
            throw new Meteor.Error('No Access!!');

        }
        Tasks.insert({
            name: name,
            createdAt: new Date(),
            userId: Meteor.userId()
        });
    },
    deleteTask: function(taskId) {
        Tasks.remove(taskId);
    }
});

// server \ main.js中的服务器端代码

Tasks=new Mongo.Collection('tasks');



Meteor.methods({
    addTask: function (name) {
        if (!Meteor.userId()) {
            throw new Meteor.Error('No Access!!');

        }
        Tasks.insert({
            name: name,
            createdAt: new Date(),
            userId: Meteor.userId()
        });
    },
    deleteTask: function taskId() {
        Tasks.remove(taskId);
    }
});

// Html页面

<head>
  <title>tasklist</title>
</head>

<body>

  {{> tasks}}
</body>

<template name="tasks">
    {{> loginButtons}}
    <h1>Add Task</h1>
    {{#if currentUser}}
    <form class="add-task">
        <label>Task Name</label>
        <input type="text" name="name" placeholder="Add Task" />
        <input type="submit" value="Submit" />
    </form>
        {{else}}
        <p>Please log in to add tasks</p>
        {{/if}}
<hr />
    <h3>Tasks</h3>
<ul>
    {{#each tasks}}
        <li>{{name}}{{#if currentUser}} <a href="#" class="delete-task">X</a>{{/if}} </li>
        {{/each}}
</ul>
</template>

请帮助,在此重新加载页面时,它首先添加并显示在网页中,如果我删除尝试删除添加的屏幕,则不会显示MongoDB中添加的任务。 当我做控制台时,会有一系列空的添加任务

1 个答案:

答案 0 :(得分:0)

如果它&#34;闪烁&#34;这通常意味着您的方法在客户端工作,但在服务器端工作。插件适用于Minimongo(客户端),但不适用于真正的MongoDB(服务器)。所以Meteor决定在Minimongo上回滚你的插页。

您的方法服务器端内部必须有问题: 您无法在方法中使用Meteor.userId()服务器端,您必须使用this.userId。 为避免错误,只在Meteor Methods客户端或服务器端使用this.userId。

// Server side
Meteor.methods({
    addTask: function (name) {
        if (!this.userId) {
            throw new Meteor.Error('No Access!!');

        }
        Tasks.insert({
            name: name,
            createdAt: new Date(),
            userId: this.userId
        });
    },
    deleteTask: function taskId() {
        Tasks.remove(taskId);
    }
});

在Meteor中,您不必复制方法客户端和服务器端。

  

应始终在客户端和服务器上加载的公共代码中定义方法,以启用Optimistic UI。

您只需在客户端和服务器上加载的文件夹中定义您的方法和集合一次。例如,您可以将代码放在名为both/的文件夹中。