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

查看:22
本文介绍了如何仅使用 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?

/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天全站免登陆