2014-01-17 40 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。 (每次移動後打開控制檯查看結果)。 –