骨干,插入模型,同时保持排序顺序

时间:2013-05-22 18:25:03

标签: javascript backbone.js

当添加新模型时(通过集合的“set”函数),我希望模型以索引维护排序顺序插入,而不是在最后。

由于

var Ts = (function () {
  var Result = Backbone.Model.extend({
   idAttribute : 'PAG_ID'
  });

  var ResultList = Backbone.Collection.extend({
    model: Result,
    comparator: function(result) {
     //console.log(result);
     return result.get('SORT_KEY');
   },
  });

var resultsCollection = new ResultList(data);

data = undefined;
var TableView = Backbone.View.extend({
 tagName: 'table',

initialize : function() {
    _.bindAll(this, 'render', 'renderRow');
    this.collection.on("add", this.renderRow, this);
},

render: function() {
  $(this.el).attr('id', 'tsTable').addClass('resulttable');
  this.renderHeader(this.collection.shift());
  this.collection.each(this.renderRow);
  return this;
},

renderHeader : function(model) {
  var col=new HeaderView({model:model});
  this.$el.append(col.render().$el);
  return this;
},

renderRow : function(model) {
  var row=new RowView({model:model});
  this.$el.append(row.render().$el);
  return this;
}

});

var HeaderView = Backbone.View.extend({
tagName: 'tr',

model: resultsCollection.models,

initialize: function() {
  this.model.on('change',this.render,this);
},

render: function() {
  var html=_.template(colTemplate,this.model.toJSON());
  this.$el.html(html);
  return this;
}

});

var RowView = Backbone.View.extend({
tagName: 'tr',

initialize: function() {
  this.model.on('all',this.render,this);
},

remove: function () {
    debug.log("Called remove event on model");
    $(this.el).remove();
},

model: resultsCollection.models,
  render: function() {
  var html=_.template(rowTemplate,this.model.toJSON());
  this.$el.html(html);
  return this;
},

attributes : function () {
  return {
    id : this.model.get('PAG_ID')
  };
}

});

var tableView = new TableView({collection: resultsCollection});
$("body").append( tableView.render().$el );


 resultsCollection.set(initialdata);
 resultsCollection.set(someotherdata, {merge: true});

我已更改为如下所示并且它有效。不确定这是否是最佳实现

 renderRow : function(model) {
  var row = new RowView({model:model});
  var index = model.get('SORT_KEY') - 1;
  row.render().$el.insertAfter(this.$el.find('tr:eq('+ index  +')'));
  return this;
}

1 个答案:

答案 0 :(得分:0)

如果您在集合上提供比较器功能,Collection.set将在拼接新模型后执行静默排序。

来自主干来源http://backbonejs.org/docs/backbone.html

set: function(models, options) {
  var sortable = this.comparator && (at == null) && options.sort !== false;
  var sortAttr = _.isString(this.comparator) ? this.comparator : null;
  ...

  if (toAdd.length) {
    if (sortable) sort = true;
    this.length += toAdd.length;
    if (at != null) {
      splice.apply(this.models, [at, 0].concat(toAdd));
    } else {
      push.apply(this.models, toAdd);
    }
  }

  if (sort) this.sort({silent: true});

这是一个小提示,表明collection.set尊重比较器。

http://jsfiddle.net/puleos/sczV3/