2014-09-19 79 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