Javascript 如何在没有会话的情况下从Meteor中的事件处理程序修改模板实例?
我正在尝试实现一个可扩展的帖子评论层次结构,如Quora,这样用户就可以点击评论并查看任何回复 为此,我希望通过在事件处理程序中切换状态来跟踪每个“注释”模板实例是否已“展开” 我可以使用整个堆栈会话变量(即,每个注释一个)来实现这一点,但这似乎很笨拙,因为在任何给定页面上都有任意数量的注释 下面是我目前正在尝试的一个片段 JS: HTML:Javascript 如何在没有会话的情况下从Meteor中的事件处理程序修改模板实例?,javascript,meteor,Javascript,Meteor,我正在尝试实现一个可扩展的帖子评论层次结构,如Quora,这样用户就可以点击评论并查看任何回复 为此,我希望通过在事件处理程序中切换状态来跟踪每个“注释”模板实例是否已“展开” 我可以使用整个堆栈会话变量(即,每个注释一个)来实现这一点,但这似乎很笨拙,因为在任何给定页面上都有任意数量的注释 下面是我目前正在尝试的一个片段 JS: HTML: {{{如果showChildComments} {{{#每个孩子都发表意见} {{>注释项目} {{/每个}} {{/if} 不幸的是,当我逐
{{{如果showChildComments}
{{{#每个孩子都发表意见}
{{>注释项目}
{{/每个}}
{{/if}
不幸的是,当我逐步介绍时,似乎在showChildComments助手中,模板实例看不到展开的变量。我确实注意到文档中说instance.data在事件映射中是只读的
是否有任何方法可以直接修改事件映射中的模板实例?您可以在其创建的事件处理程序中为模板实例创建属性。您可以访问模板实例作为事件映射函数的第二个参数
Template.comment_item.created = function() {
this.showChildren = false;
};
Template.comment_item.events({
'click .comment-content': function(event, template) {
template.showChildren = true;
}
});
然而:
<template name="comment_item">
<li class="comment comment-displayed" id="{{_id}}">
<div class="comment-body">
<div class="comment-content"> <!-- changed this to a class -->
<!-- some comment data here -->
</div>
</div>
</li>
</template>
更新:
Meteor现在允许您使用template.instance()
从助手中访问模板实例。事实上,这是提高模板可重用性的好方法
下面的示例源代码来自,由Percolate Studio的David Burles编写
Template.hello.created = function () {
// counter starts at 0
this.state = new ReactiveDict();
this.state.set('counter', 0);
};
Template.hello.helpers({
counter: function () {
return Template.instance().state.get('counter');
}
});
Template.hello.events({
'click button': function (event, template) {
// increment the counter when button is clicked
template.state.set('counter', template.state.get('counter') + 1);
}
});
很好地说明了为什么需要这种方法
将信息存储在模板实例中的优点是,您可以使模板变得越来越模块化,并减少对使用位置的依赖。会话有什么问题?你也可以用一种更传统的方式使用JQuery直接进入DOM,就像quora那样。对于你的第二个答案,你能显式地给我们js来支持你的html吗?我是一个新手,我将同意你的第一个答案,因为我不知道如何为第二个写js。(我想它可能类似于
template.find('.comment-body').append(template.comment\u-item(context))
但需要一些调整…)也许Meteor.render
带有appendChild
?
<template name="comment_item">
<li class="comment comment-displayed" id="{{_id}}">
<div class="comment-body">
<div class="comment-content"> <!-- changed this to a class -->
<!-- some comment data here -->
</div>
</div>
</li>
</template>
var context = {_id: comment_id, text: "Comment text!"};
Template.comment_item(context);
Template.hello.created = function () {
// counter starts at 0
this.state = new ReactiveDict();
this.state.set('counter', 0);
};
Template.hello.helpers({
counter: function () {
return Template.instance().state.get('counter');
}
});
Template.hello.events({
'click button': function (event, template) {
// increment the counter when button is clicked
template.state.set('counter', template.state.get('counter') + 1);
}
});