【问题标题】:Migrating to FlowRouter, need something similar to a template data context迁移到 FlowRouter,需要类似于模板数据上下文的东西
【发布时间】:2016-05-11 13:12:50
【问题描述】:

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

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

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

使用 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 来实现类似的功能?

【问题讨论】:

    标签: node.js meteor iron-router flow-router


    【解决方案1】:

    您可能需要使用模板订阅和 {{#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>
    

    【讨论】:

    • 是的,我已经这样做了。但是我没有将我的 {{> commentSection }} 包装在其中。你的评论让我这样做,所以我会接受它作为答案。谢谢!
    猜你喜欢
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多