【发布时间】:2016-12-22 22:51:48
【问题描述】:
我有一个带有正文模板的简单流星应用程序,该应用程序有一个简单的表单,可以使用title、text 和_id 创建帖子。当我创建帖子时,它会呈现在包含更新按钮的帖子模板中。在 javascript 端(客户端),我有这样的方法:
'click .update'(event){
event.preventDefault();
const target = event.target;
post = Post.find({_id: this._id}).fetch();
//send post's data to the body template so it can be rendered and updated by the user
}
基本上我想要一些东西,我可以使用它访问正文模板的实例并将其设置为title、text 和_id 值。我试过Template.instance(),但这似乎不包括这些变量。
我该怎么做呢?用户应该能够单击更新,然后以他们用于创建帖子的相同形式编辑信息(我使用 upsert 来更新而不是在帖子已经存在时创建帖子)。
带有模板的html文件:
<body>
<div class="container">
<header>
<h1>Post List</h1>
<form class="new-post">
<input type="text" name="title" placeholder="Post Title" />
<input type="text" name="text" placeholder="Post Body" />
<input hidden name="_id" />
<button value="Create">Create</button>
</form>
</header>
<ul>
{{#each posts}}
{{> post}}
{{/each}}
</ul>
</div>
</body>
<template name="post">
<li>
<ul>
<li>{{_id}}</li>
<li>{{title}}</li>
<li>{{text}}</li>
<li><button class="update" value="Update {{id}}" id='{{id}}'>Update</button></li>
<li><button class="delete" value="Delete {{id}}" id='{{id}}'>Delete</button></li>
</ul>
</li>
</template>
更新功能逻辑:
Template.body.events({
'click .update'(event){
event.preventDefault();
console.log("post id number: " + this._id);
const target =Template.instance();//I need to get the instance of the body template here (where posts are created)
posts = Posts.find({_id: this._id}).fetch();
target.title.value=posts[0].title;
target.text.value=posts[0].text;
target._id.value=posts[0]._id;
}
});
显然还有其他功能……
【问题讨论】:
-
您希望使用事件的模板参数而不是 Template.instance()。查看这篇文章了解更多信息:stackoverflow.com/a/35657873/1689286.
-
是的,这非常适合访问该模板的参数,但我需要访问另一个模板的参数。模板被定义为完全不同的 html 块。
-
这些模板是位于同一个文件中还是不同?您可以发布您的模板(相关部分)吗?
标签: javascript mongodb templates meteor