2014-01-17 42 views
0

我试图通过单击按钮来更改骨干收藏中模型的顺序。向上/向下移动骨干收藏中的模型

我在我的代码做这个:

collectionForJsonElement= Backbone.Collection.extend({ 
      //set model for collection 
      model: modelForJsonElement, 
      //set filterBy function to Collection 
      filterBy: function(searchTerm) { 
       filtered= this.filter(function(model) { 
        return ((model.get('text').toString()).indexOf(searchTerm.toString()) !== -1); 
       }); 
       return new collectionForJsonElement(filtered); 
      }, 
      //set moveUp function to Collection 
      moveUp: function(model) { // I see move up as the -1 
       var index = this.indexOf(model); 
       if (index > 0) { 
        this.remove(model, {silent: true}); // silence this to stop excess event triggers 
        this.add(model, {at: index-1}); 
       } 
      }, 
      //set moveDown function to COllection 
      moveDown: function(model) { // I see move up as the -1    
       var index = this.indexOf(model); 
       if (index < this.models.length) { 
        this.remove(model, {silent: true}); 
        this.add(model, {at: index}); 
       } 
      } 
     }); 

当我试图移动时,它工作正常。我的模型索引位置正在改变-1。但是,当我尝试向下移动时,我的模型会走到最后一个位置。

对于回,在我的骨干集,我有3个型号

One 
Two 
Three 

如果我选择三个,并点击拉升按钮,用于收集模型新订单改为:

One 
Three 
Two 

但是,如果我选择一个,然后单击向下移动按钮,对模型新订单改为:

Three 
Two 
One 

我无法弄清楚为什么它不能正常工作。 有人可以告诉我这里有什么问题吗?

回答

1

我认为你正在把模型放回原来的位置。在你的moveDown方法中。

好吧,你为什么不试试交换模型的位置,而不是将其移除并添加回来?

moveUp: function(model) { 
    var index = this.indexOf(model); 

    if (index > 0){ 
    this.swap(index, index-1); 
    } 
}, 

moveDown: function(model) { 
    var index = this.indexOf(model); 

    if (index < this.models.length) { 
    this.swap(index, index+1); 
    } 
}, 

swap: function (indexA, indexB) { 
    this.models[indexA] = this.models.splice(indexB, 1, this.models[indexA])[0]; 
} 

嗯,我仍然使用删除和添加这里的Cuz我们允许为moveUp 第一个或下移最后一个。 :)

编辑: 我才意识到在你原来的代码,你忽略了当模型的

更新了我的代码中的第一个(在为moveUp)或最后一个(在下移)的情况下, :)

+0

它会返回一个数组或骨干集合。 我尝试使用的代码,下移后,当我尝试调用方法toJSON()收集,它给我一个错误 **未捕获TypeError:不能调用未定义的方法'toJSON'** – xTMNTxRaphaelx

+0

它仍然不加工。我上面说过的同样的问题。 – xTMNTxRaphaelx

+1

http://jsfiddle.net/bFeb8/请检查此jsfiddle。我没有看到任何问题,我可以在移动模型后使用toJSON。 (每次移动后打开控制台查看结果)。 –