2

I am trying to detect when a route transition occurs. I've located this code snippet inside the latest version of Ember (v1.0.0-pre.4) that handles the transitions:

  didTransition: function(infos) {
    // Don't do any further action here if we redirected
    if (infos[infos.length-1].handler.transitioned) { return; }

    var appController = this.container.lookup('controller:application'),
        path = routePath(infos);

    set(appController, 'currentPath', path);
    this.notifyPropertyChange('url');

    if (get(this, 'namespace').LOG_TRANSITIONS) {
      Ember.Logger.log("Transitioned into '" + path + "'");
    }
  },

I set up my Ember application as window.App = Ember.Application.create().

I noticed that it calls this.notifyPropertyChange('url');, but I tried to attach an observer to my application App.Router or App.Router.router, I get an error because it does not implement Ember.Observable.

How can I detect when the route path is changed without creating a special Ember.Route for each of my routes?

CraigTeegarden
  • 8,173
  • 8
  • 38
  • 43
tina nyaa
  • 991
  • 4
  • 13
  • 25

1 Answers1

9

UPDATED ANSWER

You can now simply bind an observer on the router's didTransition event:

App.Router.reopen({
  doSomethingOnUrlChange: function() {
    console.log(this.get('url'));
  }.on('didTransition')  
});

see working example: http://jsfiddle.net/Sly7/3THD7/

DEPRECATED ANSWER BELOW

In the snippet here, there is set(appController, 'currentPath', path); I think you can put an observer on this property.

I don't know exactly where you want to be notified, but it's possible to do it in the ApplicationController itself.

App.ApplicationController = Ember.Controller.extend({

  currentPathDidChange: function(){
    // the currentPath has changed;
  }.observes('currentPath');
});

See this working fiddle for example: http://jsfiddle.net/qKrwU/

sly7_7
  • 11,961
  • 3
  • 40
  • 54
  • 2
    This observer doesn't fire when transitioning from for example `/pages/1` to `/pages/2` because the path is staying the same: `pages.page.index`. – Willem de Wit Mar 01 '13 at 10:49
  • It should be `currentPathIsChanging` not `currentPathDidChange` because when you enable logging `LOG_TRANSITIONS: true` you can see it's called just before transition. So in this method you can even stop transition and redirect to other route. – Wojciech Bednarski Apr 05 '13 at 03:46
  • @WojciechBednarski Actually, I think the meaning of the observer is that the currenPath property has changed. For me it's independent to the fact that the router effectively transitions after the currentPath has changed. Perhaps it should'nt. – sly7_7 Apr 05 '13 at 06:54