2014-09-19 75 views
2

更新:已解决此问题,并修改代码以反映我添加的更改。我也强烈推荐阅读这篇文章下面的评论。我们需要注意IronRouter的一些变化。流星ironrouter - 即使我打电话waitOn()收集返回undefined()

关键的东西是以下内容添加到您的数据功能:

if(!this.ready()) { 
    return; 
} 

我有我的应用程序与IronRouter的问题。代码如下:

/** 
* Project list view (all projects) with optional 
* filter parameter for showing projects only by 
* their category name. 
*/ 
this.route('list', { 
    path: '/:_category_slug?', 
    template: 'template_main', 
    action: function() { 
     if(this.ready()) { 
      this.render(); 
     } 
    }, 
    waitOn: function() { 
     return [ 
      Meteor.subscribe('projects'), 
      Meteor.subscribe('formations'), 
      Meteor.subscribe('categories') 
     ]; 
    }, 
    data: function() { 
     if(!this.ready()) { 
      return; 
     } 

     if(this.params._category_slug) { 
      /** 
      * Building up the query given the category slug and the language 
      */ 
      var query = {}; 
      query['slug.' + App.language] = this.params._category_slug; 

      /** 
      * Grab the category given the query 
      */ 
      var category = App.models.categories.findOne(query); 

      console.log(category); 

      return App.models.projects.find({}).fetch(); 

     } 
     else { 
      return App.models.projects.find({}).fetch(); 
     } 
    }, 
    yieldTemplates: { 
     'components_header': {to: 'header'}, 
     'views_list': {to: 'content'}, 
     'components_footer': {to: 'footer'} 
    } 
}); 

我所试图做的就是从类别蛞蝓类,所以我可以访问它的ID,这是我需要另一个查询。

问题是,当我重新加载页面和上面给出的路径匹配时,这条路线似乎运行了三次,并且第一次在控制台上记录类别变量返回未定义,然后又两次,实际的类别被打印出来。

我希望waitOn()函数在我到达数据函数的时候已经填充了所有类别,因此我可以在第一次使用查询时访问我的类别数据,但这不会发生。

任何人都可以看到在我的代码中可能会导致此问题明显显而易见的任何事情,为什么路线正在运行三次?

我使用最新版本的IronRouter(iron:[email protected])和Meteor([email protected])。

回答

2

当使用iron:router < = 0.9.3您必须激活默认的loading挂钩才能获得WAITING的预期行为,以便在呈现模板之前预订就绪。

在你的路由器配置的代码添加此:

Router.onBeforeAction("loading"); 

这意味着你不再需要提供action功能做的等待逻辑(渲染你的模板,只有当WaitList就绪)。

然而,data功能仍然会得到最初称,当订阅是没有准备好,所以你必须做自我检查:

data:function(){ 
    if(!this.ready()){ 
    return; 
    } 
    // return actual data when ready 
} 

了很多关于iron:router问题已经浮出水面对此loading挂钩的行为,并且公平地说,这很吸引人,因为当你使用waitOn时,你期望你的RouteController在显示模板之前实际上等待这些订阅,对吗?

这就是为什么在iron:[email protected]最新版本的“unstable”版本中,当它检测到您正在使用waitOn时,会自动添加loading挂钩。

我强烈建议您切换到iron:[email protected]以熟悉最新的API,它具有完整的重写和最新的好文档。

https://github.com/iron-meteor/iron-router/blob/devel/Guide.md

它基本上是落后的几个陷阱兼容,尤其是它需要你在lib/文件夹中定义的所有路由与RouteController小号一起,使其可用于客户端和服务器。

+0

谢谢你的回答。这已经解决了这个问题。 – matfin 2014-09-19 18:59:33

+0

增加了一些关于'iron:router'最新版本的评论。 – saimeunt 2014-09-19 19:05:20

+0

嗨,github的链接目前是404ing :(我很期待阅读哈哈:) – lol 2015-03-10 02:24:43