排序主干集合而不重新渲染每个视图

时间:2015-11-27 09:09:21

标签: javascript backbone.js

我想在更改状态属性后在正确的位置对我的模型进行排序和重新排序。

ItemsView

render: function(){
  for(var i=0; i < this.collection.length; i++){
    this.renderItem(this.collection.models[i]); 
  }
  return this;

},
renderItem: function( model ){
  // here I'm creating new ItemView for every model in collection
  var itemView = new ItemView({ model: model }); 
  itemView.render();
  jBone(this.el).append(itemView.el);
}

ItemView控件

initialize: function () {
  _.bindAll(this, 'updateOrderStatus');
  this.listenTo(this.model, 'change:status', this.updateOrderStatus);
},    
render: function () {
  var model = this.model.toJSON();
  this.el.innerHTML += '<p>'+model.title+'</p><div>'+model.status+'</div>';
  return this;
},
updateOrderStatus: function(newstuff){
  // Here I wanna to set directly new status of model into element, basically it is 
  // what I want to do but views are not sorted. Is possible to sort views without rerender each view in collection in new order?
  this.el.firstChild.setAttribute("class",this.model.get("status"));
  // Also I can remove view via this.remove() 
  // but is possible to render new one in right place in the list ?
},

ItemsCollection

comparator: function(item) {
  return -item.get('status');
},
initialize: function () {
  this.bind('change:status', function( model, prop ){
      model.collection.sort();
      // sort function is fired after status has changed
      // model has new position in collection
  });
}

我希望有一些方法可以在不重置或重新渲染整个集合的情况下更改视图顺序。 应用已发布在Github 感谢您的任何意见。

0 个答案:

没有答案