我正在开发一个网络应用程序来自学 Ember,我遇到了一个大问题:
页面在尝试获取 json 时停止,我的 IndexRoute 和 IndexController 感觉非常臃肿。此外,this.store.find('pokemon')
使用 RESTAdapater,并且可以卡住页面渲染任何东西(加载程序除外)长达 1.5 秒。
App.IndexRoute = Ember.Route.extend({
model: function() {
var store = this.store;
return Ember.RSVP.hash({
pokeballs: App.Pokeball.all(),
pokemon: store.find('pokemon'),
status: App.Status.all(),
levels: App.Levels
});
}
});
更新的问题:现在,我的 IndexController 是 larger than I would like , 并担任 pokeballs 和 pokemon 系列的调解人。我认为拆分 IndexController 是个好主意,这样我就有了一个 IndexController、一个 PokemonListController 和一个 PokeballListController。我遇到的问题是:
- 如果我在映射到 IndexRoute 的“/”上,我应该如何填充 PokemonListController 和 PokeballListController 的内容?
- 这实际上是个好主意吗?我是否按照预期的方式对待控制者?
网络应用演示:http://theirondeveloper.github.io/pokemon-catch-rate
Github:https://github.com/TheIronDeveloper/pokemon-catch-rate
最佳答案
一方面,您不会绑定(bind)到路由中的单个 Controller ,通常只有一个 Controller 与路由关联,但如果需要,您始终可以设置更多 Controller ,请记住它们是模型的装饰器.
App.IndexRoute = Ember.Route.extend({
model: function() {
return store.find('pokemon');
},
setupController: function(controller, model) {
var pokemonListController = this.controllerFor('pokemons');
var pokeballListController = this.controllerFor('pokeball');
controller.set('model', model); //this would be the index controller
pokemonListController.set('model', model.pokemon);
pokeballListController.set('model', model.pokeballs);
}
});
如果需要,您也可以呈现您的页面,无需等待响应,Ember 将在收到响应后处理更新您的 UI。如果您的响应太慢,用户将看到该页面和一个空列表(在本例中为空的 pokemon 列表),然后一旦请求得到解决,该列表就会填满它。
为此,只需从您的模型钩子(Hook)返回一个空数组,并异步更新它:
App.IndexRoute = Ember.Route.extend({
model: function() {
var pokemon = [];
var store = this.store;
store.find('pokemon').then(function(allPokemon) {
pokemon = allPokemon; //untested, you may need to push them instead
});
return Ember.RSVP.hash({
pokeballs: App.Pokeball.all(),
pokemon: pokemon,
status: App.Status.all(),
levels: App.Levels
});
}
});
关于javascript - 如何正确拆分 Controller 的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27716558/