1

添加新模型时(通过集合的“设置”功能),我希望将模型插入到保持排序顺序的索引处,而不是最后。

谢谢

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;
}
4

1 回答 1

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/

于 2013-05-22T18:57:09.693 回答