meteorjs iron-router waitOn并用作渲染数据

TJR*_*TJR 11 publish-subscribe meteor iron-router

我尝试在我的Template.rendered函数中获取返回的数据.

目前的代码是:

this.route('editCat', {
    layoutTemplate : 'layoutCol2Left',
    template : 'modCategoriesEdit',
    path : '/mod/categories/edit/:_id',
    yieldTemplates : _.extend(defaultYieldTemplates, {
    'navigationBackend' : {to : 'contentLeft'} 
    }),
    waitOn : function () {
         return Meteor.subscribe('oneCat', this.params._id);
    },
    data : function () {
         return Categories.findOne({_id : this.params._id});
    }
 });
Run Code Online (Sandbox Code Playgroud)

在这个块中,我等待订阅,Collection Document并将Document作为数据返回.

现在我可以在我的模板中使用返回的文档,如下所示:

<template name="modCategoriesEdit"> 
    <h1>Edit {{name}}</h1>
</template>
Run Code Online (Sandbox Code Playgroud)

我的问题是我必须在我的渲染函数中使用返回的数据,如下所示:

Template.modCategoriesEdit.rendered = function () {
    console.log(this.data);
}
Run Code Online (Sandbox Code Playgroud)

但是这会返回"null".

所以我的问题是:如何在渲染函数中访问返回的数据?

TJR*_*TJR 14

解:

只需将以下内容添加到您的iron-router route()方法中即可.

action : function () {
    if (this.ready()) {
        this.render();
    }
}
Run Code Online (Sandbox Code Playgroud)

在正确加载所有文件后,将会呈现模板.

  • 所以,如果这不是waitOn所做的,那么waitOn会做什么? (6认同)
  • 要改进您的解决方案,您还可以添加`else {this.render('YouLoadingTemplate')}` (2认同)
  • 这对我来说似乎不起作用 (2认同)

ste*_*643 10

如果要在渲染之前等待waitOn数据准备好,则有3种解决方案:

1- action为每条路线添加一个钩子

Router.map(function() 
    {
    this.route('myRoute', 
        {
        action: function() 
            {
            if (this.ready())
                this.render();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

2- onBeforeAction全局或在每条路径上使用挂钩

全局钩子的示例代码:

Router.onBeforeAction(function(pause) 
    { 
    if (!this.ready())          
        {
        pause(); 
        this.render('myLoading');
        }
    });
Run Code Online (Sandbox Code Playgroud)

myLoading (或任何名称)必须是您在某处定义的模板.

不要忘记this.render线路,否则离开路线时会出现问题(加载路线时会出现原始问题).

3-使用内置onBeforeAction('loading')挂钩

Router.configure(
    {
    loadingTemplate: 'myLoading',
    });

Router.onBeforeAction('loading');   
Run Code Online (Sandbox Code Playgroud)

myLoading (或任何名称)必须是您在某处定义的模板.