Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

meteorjs iron-router waitOn and using as data on rendered

I try to get the returned data in my Template.rendered function.

The current code is:

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});
    }
 });

In this block i wait on the subscribtion of the Collection Document and return the Document as data.

Now i can use the returned Document in my Template like this:

<template name="modCategoriesEdit"> 
    <h1>Edit {{name}}</h1>
</template>

My problem is that i have to use the returned data in my rendered function like this:

Template.modCategoriesEdit.rendered = function () {
    console.log(this.data);
}

But this returns "null".

So my question is: How is it possible to get access to the returned data in the rendered function ?

like image 967
TJR Avatar asked May 10 '14 00:05

TJR


2 Answers

Solution:

Just add the following to your iron-router route() method.

action : function () {
    if (this.ready()) {
        this.render();
    }
}

Than the Template will rendered after all is loaded correctly.

like image 141
TJR Avatar answered Oct 13 '22 02:10

TJR


There are 3 solutions if you want to wait until the waitOn data is ready before rendering:

1- Add an action hook to each route

Router.map(function() 
    {
    this.route('myRoute', 
        {
        action: function() 
            {
            if (this.ready())
                this.render();
            }
        }
    }

2- Use the onBeforeAction hook globally or on every route

Sample code for the global hook:

Router.onBeforeAction(function(pause) 
    { 
    if (!this.ready())          
        {
        pause(); 
        this.render('myLoading');
        }
    });

myLoading (or whatever name) must be a template you have defined somewhere.

Don't forget the this.render line, otherwise the problem will occur when leaving the route (while the original problem occurs when loading the route).

3- Use the built-in onBeforeAction('loading') hook

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

Router.onBeforeAction('loading');   

myLoading (or whatever name) must be a template you have defined somewhere.

like image 38
steph643 Avatar answered Oct 13 '22 02:10

steph643