ember路由,'this'指的是什么?

ember routes, what does 'this' refer to?

我熟悉 this 在 JS 中的用法。

ember 文档中用于创建路由的示例是:

 Router.map(function() {
 this.route('about', { path: '/about' });
 this.route('favorites', { path: '/favs' });
 });

他们的解释有点不尽如人意:

"When calling map(), you should pass a function that will be invoked with the value this set to an object which you can use to create routes."

什么对象?全局路由器对象?

是的。正如您所说,它是 Router 对象。这是在 router.js 文件顶部定义的。但我们不会在 map 函数中使用属性。

我们可以利用Router中的属性和它的方法,就像下面我演示的didTransition回调,它是在所有转换完成后有用的回调。

const Router = Ember.Router.extend({
    location: config.locationType,
    rootURL: config.rootURL,
    myService:Ember.inject.service(),    
    didTransition() {
        this._super(...arguments);
        console.log(' After all the router transition complete ', ...arguments);
        //if you override anywhere didTransition dont forget to return true to allow chain to reach here
        return true;
    }
});

如果你打印出 this 或者如果你调试代码,你会看到 map 方法中的 this 实际上是 DSL object. It is hidden down in the api; what really occurs is that; Ember.Router creates an instance of DSL and generates corresponding path matches via this object and passes it down to the actual router 的一个实例,由 Ember.Router 本身。当然,在我们的应用程序中,我们只处理 Ember.Router 而不知道其他 类 的详细信息。如果您有兴趣,可以从我提供的链接中跟踪源代码(这是我一周前为一些工作所做的)。