2015-09-01 52 views
1

我是新来的流星,试图做一个简单的博客应用程序。但我的插入功能似乎没有正常工作。这是我的代码。MeteorJS插入功能不起作用

这是我的模板

<template name="addpost"> 
    <div class="container"> 
    <h1> Add New Post</h1> 
    <form class="new-post"> 
     <label class="title"> 
     Title: 
     <input type="text" name="title" placeholder="Type to add new tasks" /> 
     </label> 
     <label class="post-content"> 
     Write here: 
     <input type="text" name="body" placeholder="Type to add new tasks" /> 
     <button class="add-post">Add Post</button> 
     </label> 

    </form> 
    </div> 
</template> 

JS文件内容

Posts = new Meteor.Collection("posts"); 

if (Meteor.isClient) { 

    Template.addpost.events({ 
    "submit .new-post": function(event){ 

     var title = event.target.title.value; 
     var body = event.target.body.value; 

     Meteor.call("addPost", title, body); 
    } 
    }); 
} 


Meteor.methods({ 
    addPost: function(title, body){ 
    Posts.insert({ 
     title: title, 
     body: body, 
     createdAt : new Date() 
    }); 
    } 
}); 

我没有删除和自动发布不安全包。下面是mongoDB查询输出。

enter image description here

回答

2

默认情况下,当您提交它使另一个HTTP请求这将刷新页面,并阻止任何流星在做一个形式。为了避免这种情况,你需要防止默认动作:

Template.addpost.events({ 
    submit: function(event) { 
    event.preventDefault(); 
    // the rest of your code goes here 
    } 
}); 

除此之外,你的代码正确为我工作。您可以在Web控制台中通过Posts.find().fetch()或通过meteor shell进行验证。

+0

Web控制台现在说“错误调用方法'addPost':找不到方法[404]” – TA3

+0

您发布问题后可能会有一些错字,因为它对我来说工作正常。如果你可以在[meteorpad](http://meteorpad.com/)上重现问题,或者给出一个github回购的链接,我可以再看一次。 –

+0

github回购:https://github.com/TA-3/blog-app – TA3