如何使用操作对模型重新排序

How to reorder my model with actions

本文关键字:排序 新排序 何使用 操作 作对 模型      更新时间:2023-09-26

我想用向上和向下按钮重新排序我的模型。执行这些操作的余烬方法是什么?

这是一个jsbin:http://emberjs.jsbin.com/haxegihaye/9/

谢谢你的帮助。

为了更清楚,我只想在我的"模型"中选择一个数组项目,然后向上或向下选择该项目。我想,我只需要更改数组中项目的索引,但我不知道如何使用余烬执行此操作?

您可以使用

sortProperties: propertyName & sortAscending: true/false

这是演示

我已经修改了您的模型以包含id字段,以便按id排序。

App.PostsRoute = Ember.Route.extend({
    model: function() {
      return [
        {id: 1, title: 'post 1'},
        {id: 2,title: 'post 2'},
        {id: 3,title: 'post 3'},
        {id: 4,title: 'post 4'},
        {id: 5,title: 'post 5'}
      ];
    }
});

您的控制器将像这样 -

App.PostsController = Ember.ArrayController.extend({
  itemController: 'post',

  selectedPost: null,
  actions: {
    up: function() {
      this.set('sortProperties', ['id']);
      this.set('sortAscending', true);
      if (this.get('selectedPost')) {
        var selectedPost = this.get('selectedPost');
        var index = this.get('model').lastIndexOf(selectedPost); 
        if (index > 1) {
          // up
        }
      }
    },
    down: function() {
     this.set('sortProperties', ['id']);
     this.set('sortAscending', false);
      if (this.get('selectedPost')) {
        var selectedPost = this.get('selectedPost');
        var index = this.get('model').lastIndexOf(selectedPost); 
        if (index < this.get('model.length')) {
          // down
        }
      }
    }
  }
});