如何仅使用Ember中的路线对模型进行排序? [英] How do I sort models using only a route in Ember?

查看:81
本文介绍了如何仅使用Ember中的路线对模型进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,您可以使用ArrayControllers(在1.13.0版中弃用),并且我们知道很快不会在ember中推荐使用控制器。

In the past you could use ArrayControllers (deprecated in 1.13.0), and we know that shortly controllers won't be recommended in ember. Is it currently possible to sort my model using only my route?

ie

/routes/orders.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() { return this.store.findAll('order'); }
});

我如何以名称为例,但仅使用路线?

How would I sort by 'name' as an example, but only using a route?

请注意,此问题类似于如何在Ember.js中对模型进行排序?-但是可以通过任何方法进行,而我的问题是仅使用路由(如果可能)进行建模。

Note that this question is similar to How to sort model in Ember.js? - but there it is via any method, whereas my question is specific to doing it only using a route (if possible).

推荐答案

Ember 2.0的新答案

尽管问题仍然存在,但torazaburo的回答在Ember 2.0之前运行良好。现在最好的答案是不要仅使用路线对模型进行排序-而是在控制器中进行排序,或者如果您不想在组件中使用控制器,则进行排序。

Although the question still stands and torazaburo's answer works great before Ember 2.0. The best answer now is "don't sort a model using only a route" - instead do the sorting in a controller, or if you don't want to use a controller then in a component.

Ember 2.0之后的重载行为有一个很大的陷阱。如果存储中已经有记录,并且您未在findAll的选项中指定{reload:true},则findAll方法将立即使用这些记录进行解析,这意味着则仅对已经拥有的那些记录进行排序。因此,当实际的后台请求仍在进行时,您的模型可以返回有限数量的记录。有关更多信息,请参见DS Store文档。

There is a big 'gotcha' with the reload behaviour post Ember 2.0. If there are already records in the store, and you do not specify { reload: true } in the options of findAll, then the findAll method will instantly resolve with those records, meaning the then only sorts with those records you already had. So your model could return with a limited number of records while the actual background request is still going on. See DS Store docs for further info.

因此,基于先前接受的答案的改进代码为:

The improved code based on the previously accepted answer is therefore:

export default Ember.Route.extend({
  model: function() { 
    return this.store.findAll('order', { reload: true }).
      then(orders => orders.sortBy('name'));
    }
});

但是如前所述,我认为最好的做法是不完全依赖路线,而是在控制器或组件中使用计算排序。

But as previously mentioned, I think the best course of action is to not rely solely on the route, but instead use computed sort in either a controller or a component.

这篇关于如何仅使用Ember中的路线对模型进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆