2013-04-15 60 views
6

我正在嘗試觀察路徑變化,以應用一些渲染後的常見操作。這個想法是有一個類似於onload的功能,但是因爲我們使用單頁應用程序,所以需要在每個路線更改時觸發它。 (可作用域爲新視圖)Obversing route change to apply equivalent to onload

我發現如何觀察currentPath變化:

App.ApplicationController = Ember.Controller.extend({ 
    currentPathDidChange: function() { 
    prettyPrint() 
    }.observes('currentPath'); 
}); 

雖然這部作品在某些情況下好,它就會被觸發時的路線變化,但仍早應用內容更改,因爲它似乎在內容呈現之前附加。

有關實現此目標的最佳實踐的任何想法?

+2

我留下了一個答案,但我會建議在很多情況下,如果您必須等待視圖才能使用DOM,它實際上是一種反模式。也許有更好的地方來放置你正在做的任何DOM操作,比如某個視圖的'didInsertElement'? –

+0

如果你實現了視圖,你可以在['didInsertElement'](http://emberjs.com/api/classes/Ember.View.html#event_didInsertElement) – MilkyWayJoe

回答

12

你有沒有試過推遲Ember.run.schedule代碼?例如,

App.ApplicationController = Ember.Controller.extend({ 
    currentPathDidChange: function() { 
    Ember.run.schedule('afterRender', this, function() { 
     prettyPrint(); 
    }); 
    }.observes('currentPath') 
}); 
+0

謝謝!這對我有效。 – John

0

由於deprecation of Controllers in Ember 1.x找到路由器的URL將是未來的證明您的應用程序的好方法。您可以在ember-cli做到這一點,像這樣:

// similar to onLoad event behavior 
export default Ember.Route.extend({ 
    afterModel: function (model){ 
    Ember.run.next(() => { 
     console.log(this.get('router.url')); 
    }); 
    } 
}); 

// hacky way to get current url on each transition 
export default Ember.Route.extend({ 
    actions: { 
    didTransition: function() { 
     Ember.run.next(() => { 
     console.log(this.get('router.url')); 
     }); 
    } 
    } 
}); 

這將記錄:/posts/posts/3/comments等。

+0

棄用頁面沒有提及控制器將被棄用。只是'ArrayControllers'和'ObjectControllers',但不是所有的控制器。 – mikefrey

+0

的確如此,但我認爲最終這種邏輯應該以可路由組件或路由結束。您目前可以(1.13.6)使用沒有任何棄用警告的Controller,但我認爲這可能會在Ember 2中改變(目前處於測試階段)。 –