meteorjs iron-router waitOn and using as data on rendered

后端 未结 4 682
长情又很酷
长情又很酷 2020-12-14 22:46

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

The current code is:

this.route(\'editCat\', {
    layoutTemplate : \'l         


        
相关标签:
4条回答
  • 2020-12-14 23:28

    Like @Sean said, the right solution is to use a loading template:

    Router.onBeforeAction("loading");
    

    But if you don't want it, like me, I came up with this solution:

    Template.xxx.rendered = function() {
        var self = this;
    
        this.autorun(function(a) {
            var data = Template.currentData(self.view);
            if(!data) return;
    
            console.log("has data! do stuff...");
            console.dir(data);
            //...
        });
    }
    

    Template.currentData is reactive, so in the first time it is null and in the second it has your data.

    Hope it helps.

    -- Tested on Meteor v1.0 with Iron Router v1.0

    0 讨论(0)
  • 2020-12-14 23:30

    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.

    0 讨论(0)
  • 2020-12-14 23:30

    Using the action hook to check for this.ready() works, but it looks like the official way to do this is to call the following:

    Router.onBeforeAction("loading");
    

    Reference: https://github.com/EventedMind/iron-router/issues/679

    0 讨论(0)
  • 2020-12-14 23:41

    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.

    0 讨论(0)
提交回复
热议问题