javascript - IronRouter 获取布局中的数据

标签 javascript meteor iron-router meteor-blaze

我们有一个布局需要像这样在我们的 Controller 中定义的当前数据:

TripController = RouteController.extend({
    layoutTemplate: 'tripLayout',
    data: function () {
        return Trips.findOne({_id: this.params._id});
    }
});

我们的问题看起来像是一场数据竞赛:

大多数时候 Template.currentData() 为 null 但有时(主要是在调试时)它是我们定义的 data。 只有当我们在 tripLayout 中重新加载页面时才会出现此问题,但当我们从另一个页面进入行程布局时不会出现此问题。

请注意,我们认为 `TripController 已加载,因为 Controller 参数已正确设置。

Template.tripLayout.onRendered(function() { // note, this is the layout template
    Iron.controller.params._id // correct id
    Template.currentData() // null
});

我们试图实现的是一种拆分布局,其中右侧始终相同,左侧由产量填充(见屏幕截图)layout

更新 (这个更新是错误的)

我想我发现了错误:

waitOn: function () {
    return [Meteor.subscribe('public-trips'),
        Meteor.subscribe('my-trips')];
}

一旦我删除数组(因此只有一个订阅),

data: function () {
    return Trips.find({}).fetch();
}

不再返回 0。我会仔细研究一下。

更新 2

所以我最初的假设是错误的,只订阅一个没有帮助。这实际上只是一个竞争条件。

更新 3

我设法重现它:meteorpad

在警报中,它显示它拥有的玩家数量。第一次是 0,然后是 6。但 0 不应该出现,因为我们“等待”它?!

最佳答案

我们设法解决了“问题”(这是预期的行为,但我们找到了解决方法)!详情在 https://github.com/iron-meteor/iron-router/issues/1464#issuecomment-158738943 :

Alright, here's how we fixed that problem:

The first important thing is to to include the action function like so:

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

That worked for almost everything, but we still had some issues. In our case, it was about templates that aren't rendered in using yield, and are thus out of Iron Router's control. Switch these over to content regions (using {{yield 'contentRegionName'}}) and then explicitly render them in the action function like so:

action: function() {
    if (this.ready()) {
        this.render();
        this.render('contentRegionTemplate', {to: 'contentRegionName'});
    } 
}

You need these action functions, since the waitOn only means that the subs defined there will be added to a waitlist, but not that that waitlist will be waited on. Essentially, what happens now is that your action function is called twice, thanks to reactivity, and the templates are only rendered once the data is ready.

关于javascript - IronRouter 获取布局中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33052937/

相关文章:

javascript - 如何将 HTML 文件转换为 GIF

node.js - 将 Meteor 应用程序部署到 Elastic Beanstalk

jquery - Meteor Jquery 点击事件未在移动设备上注册

meteor - 如何做 meteor 铁路由器服务器端重定向?

javascript - Iron Router 在实际更改模板之前 Hook 路线

meteor - 帐户输入 meteor 布局

javascript - 需要有关 jquery 和 json 的指导

javascript - 替换正则表达式后,我失去了对 <input> 的关注

javascript - 显示基于 $localStorage 的字段

javascript - 铁路由器 : render template in named yield from event