开发者

Extract Model from a BackboneJS Collection/UnderscoreJS array

开发者 https://www.devze.com 2023-04-09 05:50 出处:网络
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 direc

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

精彩评论

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

关注公众号