2

所以我读了很多关于 Iron Router 与 FlowRouter 的讨论。

我使用 Iron Router 开始了我的项目,但后来我改变了主意,我目前正在迁移到 FlowRouter。

在我开始迁移我的应用程序的评论部分之前,一切都很顺利。你看,这个部分在应用程序上被重复使用了几次,它作为新闻、帖子、照片、视频等的评论部分。

使用 IR 的数据上下文的示例:

Router.route('/news/:slug', {
   name: 'newsItem',
   waitOn: function() { Meteor.subscribe('news.single', this.params.slug) },
   data: function() {
      return News.findOne({slug: this.params.slug});
   }
});

<template name="newsItem">
  <p>{{title}}</p>
  <p>{{body}}</p>
  {{> commentSection}}
</template>

评论集合模式有一个“类型”(知道该评论属于什么类型的“事物”,新闻、照片等)。该类型是在commentSection 模板的“form .submit”事件中设置的。例子:

'submit form': function(e, template) {
  e.preventDefault();
  var $body = $(e.target).find('[name=body]');
  console.log(template.data.type);
  var comment = {
    type: template.data.type,
    parentId: template.data._id,
    parentSlug: template.data.slug,
    body: $body.val()
  };
  Meteor.call('insertComment', comment, function(error, commentId) {
    if (error){
      alert(error.reason);
    } else {
      $body.val('');
    }
  });
}

这是因为模板数据上下文包含 News 项目,而该项目又具有一个 type 属性。

如果按照官方指南的建议,仅使用 Flow Router 而不在模板上设置数据,我如何才能实现类似的功能?

4

1 回答 1

2

您可能需要使用模板订阅和 {{#with}} 助手。

Template.newsItem.onCreated( function() {
    Template.instance().subscribe('news.single', FlowRouter.current().params.slug);
});

Template.newsItem.helpers({
    item() {
        let item = News.findOne();
        if( item ) {
            return item;
        }
    }
});

<template name="newsItem">
    {{#with item}}
        <!-- Your existing stuff -->
    {{/with}}
</template>
于 2016-02-02T16:29:58.920 回答