开发者

Extract Model from a BackboneJS Collection/UnderscoreJS array

I've been checking the docs of Backbone and Underscore for a "proper" way to extract a model (remove the value and have it returned) fro开发者_C百科m a collection. I know I can do this through direct access via the "models" array attribute and the splice method, but is that stepping around some built-in way I'm overlooking?


It is critical that you use the built-in "remove" method on the collection. Remove does the following:

  • updates the built-in index that's used for collection.getByCid()
  • updates the built-in index that's used for collection.get()
  • decrements collection.length
  • removes the model (or models if you pass in an array of models, ids, or cids)
  • triggers the remove event on the collection

If you manipulate the models inside the collection directly, none of the things above will happen.

More info on remove: http://documentcloud.github.com/backbone/#Collection-remove


From your comment:

I'm looking to actually remove the model at say index 5 and have that value returned.

Try this:

// given: myCollection is a Backbone collection

var item = myCollection.at(5);
myCollection.remove(item);

// ... now, do whatever else with `item`...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜