I'm trying to observe the route change to apply some common action once rendered. The idea is to have a feature similar to the onload but as we use a single-page app this needs to be triggered on each route changes. (could be scoped to the new view)

I found how to observe the currentPath changes:

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

While this works good in some cases, it gets triggered when the route changes, but still to early to apply content changes as it seem to append before the content gets rendered.

Any idea on the best practice to achieve such goal?

有帮助吗?

解决方案

Have you tried deferring the code with Ember.run.schedule? For instance,

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

其他提示

Due to the deprecation of Controllers in Ember 1.x finding the url in the router would be a good way to future proof your apps. You can do this in ember-cli like so:

// 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'));
      });
    }
  }
});

This will log: /posts and /posts/3/comments ect.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top