在EmberJS 1.0.0-pre.4中检测路由转换

tin*_*yaa 2 ember.js ember-router

我试图检测何时发生路由转换.我已将此代码段放在最新版本的Ember(v1.0.0-pre.4)中,用于处理转换:

  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 + "'");
    }
  },
Run Code Online (Sandbox Code Playgroud)

我将我的Ember应用程序设置为window.App = Ember.Application.create().

我注意到它调用了this.notifyPropertyChange('url');,但我试图将一个观察者附加到我的应用程序,App.Router或者App.Router.router我得到一个错误,因为它没有实现Ember.Observable.

如何更改路径路径而不为每条路线创建特殊的Ember.Route?

sly*_*7_7 9

更新的答案

您现在可以简单地在路由器的didTransition事件上绑定观察者:

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

见工作实例:http://jsfiddle.net/Sly7/3THD7/

以下是弃用的答案

在这里的片段中,set(appController, 'currentPath', path);我认为你可以把观察者放在这个属性上.

我不知道您希望收到通知的确切位置,但可以在ApplicationController本身中执行此操作.

App.ApplicationController = Ember.Controller.extend({

  currentPathDidChange: function(){
    // the currentPath has changed;
  }.observes('currentPath');
});
Run Code Online (Sandbox Code Playgroud)

看到这个工作小提琴例如:http://jsfiddle.net/qKrwU/

  • 当从例如`/ pages/1`转换到`/ pages/2`时,这个观察者不会触发,因为路径保持不变:`pages.page.index`. (2认同)