Access to the parent route model in Ember.js

I am trying to write a route that needs access to its parent model. I use this.modelFor() , but when I do this, the parent model is not fully loaded, so all its properties contain null .

This is a router with two dynamic segments:

 MGames.Router.map(function () { this.resource('games', function () { this.resource ('game', {path: '/:game_id'}, function () { this.resource('board', {path: '/boards/:board_id'}); }); }); }); 

This is my GameRoute that works great:

 MGames.GameRoute = Ember.Route.extend ({ model: function (params) { return MGames.Game.find(params.game_id); } }); 

And finally, this is a children's route that needs access to the Game model, and this is what I wrote. But no matter what I do, console.log() always prints null . If I check the game variable, the isLoad property isLoad always null:

 MGames.BoardRoute = Ember.Route.extend ({ model: function (params) { var game = this.modelFor ('game'); console.log (game.get("id")); return MGames.Board.find(game.get("id"), params.board_id); } }); 

Am I doing something wrong, or (as I suspect) am I missing some Ember concept?

+8
javascript
source share
1 answer

This part of your code looks good. Your assumptions are true that the nested route should get the parent model through modelFor .

I suspect your search method is the source of the error. I looked at your previous question , and I assume that Game.find (?) Game.find used here

The problem is related to Promises . Amber router understands the asynchronous nature of the model hook. But he relies on you returning Promise to do this. You are currently using the jQuery promise, but you are immediately returning the game object to its uninitialized state. The request is loaded from the server, but it is assumed that the model() hook is allowed before this happens.

You want to directly return jQuery Promise from your model hook. Parse in the first then and return it as the result.

Here is your modified Game.find . The same principles apply to other seekers.

 find: function (game, board) { url = [MGames.GAMES_API_URL]; url.push ('games'); url.push (game); url.push ('boards'); url.push (board); url = url.join('/'); return $.getJSON(url) .then(function(response) { var game = MGames.Game.create({isLoaded: false}); game.setProperties(response); game.set('isLoaded', true); return game; }); } 

Please note that the game object is returned as is. Amber realizes that when a promise is resolved (returning anything other than a promise), this result is a model for the model() hook. This game object is a model that will now be available in modelFor via a nested route.

+6
source share

All Articles