Home > Article > Web Front-end > How to Load Multiple Models on the Same Route in EmberJS?
In EmberJS, it's sometimes necessary to load multiple unrelated models into a single route. This concept can be confusing for newcomers to client-side MVC frameworks. To help clarify, this guide provides a detailed explanation of how to handle this scenario and the appropriate approach to take based on the route's dependency on URL parameters.
Before returning multiple models in the model hook, it's crucial to determine if the route loads dynamic data based on a slug :id in the URL. If the answer is yes, loading multiple models from the same hook should be avoided. This is because Ember's linking mechanism allows you to specify a model when transitioning to the route, which would bypass the model hook and use the provided model instead. This could cause issues since you would expect multiple models, but only one would be available.
If the route loads dynamic data based on a URL parameter, it's recommended to load multiple models using setupController/afterModel instead of the model hook.
SetupController allows you to modify the model before the controller is created. You can use this to add extra models to the controller. For example:
App.IndexRoute = Ember.Route.extend({ model: function(params) { return $.getJSON('/books/' + params.id); }, setupController: function(controller, model){ this._super(controller,model); controller.set('model2', {bird:'is the word'}); } });
AfterModel allows you to perform any asynchronous operations after a model has been loaded. You can use this to load additional models and use Ember promises to manage the asynchronous requests. For example:
App.IndexRoute = Ember.Route.extend({ model: function(params) { return $.getJSON('/books/' + params.id); }, afterModel: function(){ var self = this; return $.getJSON('/authors').then(function(result){ self.set('authors', result); }); }, setupController: function(controller, model){ this._super(controller,model); controller.set('authors', this.get('authors')); } });
If the route does not load dynamic data based on a URL parameter, you can go ahead and return multiple models from the route's model hook. The syntax is straightforward:
App.IndexRoute = Ember.Route.extend({ model: function() { return { model1: ['red', 'yellow', 'blue'], model2: ['green', 'purple', 'white'] }; } });
If the model loading involves promises, you can use Ember RSVP to handle the asynchronous nature of the requests. For example, using Ember Data:
App.IndexRoute = Ember.Route.extend({ var store = this.store; model: function() { return Ember.RSVP.hash({ cats: store.find('cat'), dogs: store.find('dog') }); } });
This approach allows you to load multiple models concurrently and handle them as a single object in the template.
The above is the detailed content of How to Load Multiple Models on the Same Route in EmberJS?. For more information, please follow other related articles on the PHP Chinese website!