【问题标题】:Why object is not available on template when iron-router is returning that object当铁路由器返回该对象时,为什么该对象在模板上不可用
【发布时间】:2014-12-14 09:05:57
【问题描述】:

我有一个如下所示的页面的路由控制器,它返回一个对象。但是在渲染模板时我找不到这个对象,但是当我使用 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 的原因,因为 cmets 可用。当我在 RouteController 上使用 console.log 检查时,MyObj 被正确返回。

编辑: 我可以在页面加载时在控制台中找到 myObj,因此在渲染模板时,myObj 仍然对模板不可用。

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

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

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

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

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

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

    【讨论】:

    • 是的,我可以在控制台中找到该对象。那么如何确保模板等待订阅准备好呢?我认为在数据块中,“准备好”正在做这项工作,即它仅在 MyObj 订阅准备好时返回。但显然这并没有发生。
    • 我也尝试过将订阅放在waitOn中,但它仍然无法正常工作
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 2012-01-05
      • 2021-05-28
      • 2020-02-06
      • 1970-01-01
      相关资源
      最近更新 更多