当iron-router返回该对象时,为什么对象在模板上不可用

时间:2014-12-14 09:05:57

标签: meteor iron-router

我有一个像下面给出的页面的路由控制器,它返回一个对象。但是在渲染模板时我无法找到此对象,但是当我使用console.log打印时,obecjt正在正确返回到模板。

  MyPageController = RouteController.extend({
    template: 'myPage',
    increment: 5,
    commentsLimit: function() {
        return parseInt(this.params.commentsLimit) || this.increment;
    },
    findOptions: function() {
        return {sort: this.sort, limit: this.commentsLimit()};
    },
    subscriptions: function() {
        this.myObjectSub = Meteor.subscribe('singleObject', this.params._id);
        this.commentsSub = Meteor.subscribe('comments', this.params._id, this.findOptions());
    },
    comments: function() {
        return Comments.find({myObjectId: this.params._id}, this.findOptions());
    },
    myObj: function() {
        return MyObects.findOne(this.params._id);
    },
    data: function() {
        var hasMore = this.comments().count() === this.commentsLimit();

        return {
            myObj: this.myObj(),
            comments: this.comments(),
            ready: this.myObjectSub.ready,
            nextPath: hasMore ? this.nextPath() : null
        };
    },
    sort: {submitted: -1, _id: -1},
    nextPath: function() {
        return Router.routes.myPage.path({_id:this.params._id, commentsLimit: this.commentsLimit() + this.increment});
    }
});

我的路线定义如下:

Router.route('/myobjects/:_id/:commentsLimit?', {
name: 'myPage',
controller: MyPageController
});

我无法找到MyPage模板找不到MyObject的原因,因为注释可用。当我在RouteController上使用console.log检查时,MyObj被正确返回。

修改 我可以在加载页面时在控制台中找到myObj,因此在呈现模板时,模板仍然无法使用myObj。

因此,当我以这种形式返回数据时,找到myObj并加载正常。

data: function() {return MyObjects.findOne(this.params._id);}

但是当我想要返回多个变量时,我可以找到其他变量,例如comments& nextPath但不是myObj ??为什么会这样?

return {
        myObj: this.myObj(),
        comments: this.comments(),
        ready: this.myObjectSub.ready,
        nextPath: hasMore ? this.nextPath() : null
    };

2 个答案:

答案 0 :(得分:1)

当模板即将在浏览器中显示时,您可以开始订阅。然后将直接呈现模板(在订阅准备好之前!),此时,浏览器尚未收到该对象。这就是为什么MyObects.findOne(this.params._id)在模板中评估为null的原因,但是当你稍后在控制台中评估等效MyObects.findOne调用时(当订阅准备就绪时),你期望的对象。

答案 1 :(得分:0)

由于在加载模板时obj可能不可用,您可以执行以下操作以在数据可用时反应性地加载所有对象值:

Template.myPage.helpers({

    _id: function() {
        return this.myObj ? this.myObj._id : '';
    },
    title: function() {
        return this.myObj ? this.myObj.title : '';
    },
});