SeattleDucati
SeattleDucati

Reputation: 293

ember routes, what does 'this' refer to?

I'm familiar with how this is used in JS.

The example from the ember docs for creating routes is:

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

Their explanation leaves a bit to be desired:

"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."

What object? A global router object?

Upvotes: 0

Views: 87

Answers (2)

feanor07
feanor07

Reputation: 3368

If you print out this or if you debug the code you will see that this within map method is in fact an instance of 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 encapsulated by Ember.Router itself. Of course within our app we only deal with Ember.Router and does not know about the details of other classes. If you are interested you can track the source code from the links I have provided (that is what I had done for some work just a week ago).

Upvotes: 1

Ember Freak
Ember Freak

Reputation: 12872

Yes. Like you said it's Router object. that's defined in router.js file top place. but we will not use properties inside map function.

We can make use of properties and its methods in Router, like the below I demonstrated didTransition callback which is useful callback after all the transition completed.

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

Upvotes: 1

Related Questions