2011-06-06 41 views

回答

18

這是今天的一個很好的問題,仍然具有現實意義,所以值得回答。

當你問這個問題時,我的答案中使用的功能是不存在的,但現在這樣做很簡單。

無論如何,假設您的收藏夾名爲myCollection,並且已經存儲了3個模型。讓我們也說你有一個名爲newModel的新模型,你想用它來替換集合中現有的中間模型。要更換中間模型,離開第一和第三模式不變,你可以這樣做:

myCollection.remove(myCollection.at(1)); 

myCollection.add(newModel, {at: 1}); 

這將不正是你想要的東西,提高remove事件消失,模型和add事件的更換,這也是你想要的。

0

一種方法是直接修改collection.models數組,然後調用

collection.refresh(collection.models) 

然而,這將調出一個add事件列出每個模型。理想情況下,我想爲已刪除的模型調用remove事件,併爲新的模型調用add事件。我不知道這是否是可能的,而無需使用comparator和我的模型加算指標...

2

你可以引進骨幹集合中replaceAt功能,將是這個樣子:

replaceAt : function(model, options, replaceIndex) { 
     this._replaceAt(model, options, replaceIndex); 
     return this; 
    }, 

    _replaceAt : function(model, options, replaceIndex) { 

     options || (options = {}); 
     if (!(model instanceof Backbone.Model)) { 
     model = new this.model(model, {collection: this}); 
     } 
     var already = this.getByCid(model); 
     if (already) throw new Error(["Can't add the same model to a set twice", already.id]); 
     this._byId[model.id] = model; 
     this._byCid[model.cid] = model; 
     model.collection = this; 
     replacedModel = this.at(replaceIndex) 
     this.models.splice(replaceIndex, 1, model); 
     this._cleanModel(replacedModel, options); 
     model.bind('all', this._boundOnModelEvent); 
     if (!options.silent) model.trigger('add', model, this, options); 
     return model; 
    }, 

    _cleanModel : function (model, options) { 
     if(!model) return null; 
     delete this._byId[model.id]; 
     delete this._byCid[model.cid]; 
     delete model.collection; 
     if(!options.silent) model.trigger('remove', model, this, options); 
     model.unbind('all', this._boundOnModelEvent); 
     return model; 
    }, 

其基於_add和_remove方法。它應該激發您正在尋找的適當事件,但我沒有爲此進行測試。我測試了它會在適當的位置替換集合中的元素。

(使用骨幹.3.3)

+0

嗯,也許我應該寫一個'LinearCollection'子類,我的目的。 – 2011-06-06 23:24:16

0

雖然這個問題很久以前就問過了,但即使在今天也是如此。
而且其實很簡單。

  1. 我們需要獲取集合中的舊模型索引。
  2. ,然後添加新的到集合在同一索引位置和合並

看看下面的例子:

var index = collection.indexOf(oldModel); //1 
collection.add(newModel, {at: index, merge: true}); //2 

希望這將有助於有人爲...
好運!

+1

我不相信這是正確的。與'collection.set'一起使用時,'merge:true'接受新模型的屬性,並將它們設置在目標索引處的現有模型上。與'collection.add'一起使用,它不起作用(至少在Backbone 1.1.0中)。 – 2013-12-12 20:29:11

+1

Hi Trevor,我和一位朋友進行了這方面的討論,並指出他在骨幹官方網站中的這個鏈接:[backbone add collection](http://backbonejs.org/#Collection-add)。順便說一句,我嘗試了上面的代碼和它的工作。無論如何謝謝你的反饋。 – 2014-01-12 11:11:10

5

有內置骨幹一種簡單的機制來處理這個問題

myCollection.add(newModel, {merge: true});

+0

這應該是被接受的答案。 – 2014-10-20 19:39:47

+1

合併和替換是不同的行爲。 OP詢問如何更換。不過,我同意這個答案是資料性的,並且解決了另一個需求。 Upvoted。 – dcarson 2014-12-01 21:55:33

+2

我不同意。 OP詢問了這個答案沒有解決的具體問題。此外,答案並沒有說明它沒有解決OP的原始問題。它可能會混淆其他讀者。對於另一個問題,這將是一個很好的答案。 Downvoted。 – 2015-02-26 13:20:51

相關問題