Home >Web Front-end >JS Tutorial >How to Effectively Load Multiple Models on the Same Route in EmberJS?
EmberJS: Loading Multiple Models on the Same Route
When using EmberJS, you may encounter situations where you need to load multiple unrelated models on the same route. This can be confusing, especially if you're new to client-side MVC frameworks.
Caution:
Before attempting to load multiple models, consider the following:
Loading Multiple Models When Appropriate:
If the route does not have a dynamic URL, you can return multiple models from the route's model hook. For example:
App.IndexRoute = Ember.Route.extend({ model: function() { return { model1: ['red', 'yellow', 'blue'], model2: ['green', 'purple', 'white'] }; } });
Loading Multiple Models with Promises:
If fetching data involves promises, you can use the RSVP.hash method in the model hook:
App.IndexRoute = Ember.Route.extend({ model: function() { return Ember.RSVP.hash({ model1: promise1, model2: promise2 }); } });
Loading Models with Ember Data:
If using Ember Data, you can find multiple models in the model hook:
App.IndexRoute = Ember.Route.extend({ var store = this.store; model: function() { return Ember.RSVP.hash({ cats: store.find('cat'), dogs: store.find('dog') }); } });
Alternative Approach (more suitable for handling dynamic routes):
Instead of loading multiple models from the model hook, you can use the setupController or afterModel hooks to set model properties on the controller:
Setup Controller Method:
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'}); } });
After Model Method:
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')); } });
This approach ensures that the models are available in the setupController hook, where you can safely assign them to controller properties.
The above is the detailed content of How to Effectively Load Multiple Models on the Same Route in EmberJS?. For more information, please follow other related articles on the PHP Chinese website!