ChatGPT解决这个技术问题 Extra ChatGPT

Backbone.js: How to get the index of a model in a Backbone Collection?

Is there a way to find the index of a model within a collection?

Let's say in a view we have a model we're working on, could that model spit out it's index within the collection it's currently inside of? I'd like to do this because I want to access the model above or below the current target.

In other words is there something like:

index = this.model.index
modelAbove = this.collection.at( index-1 )

My data is a nested set so I can just do a search on the "lft" or "rgt" columns, but I didn't want to reinvent the wheel if Backbone already has this info available.


D
Derick Bailey

yes, backbone provides access to many underscore.js methods on models and collections, including an indexOf method on collections. it also provides an at method like you've shown.

var index = this.collection.indexOf(this.model);
var modelAbove = this.collection.at(index-1);

Thanks for clearing this up! You know, it would be so great if the .collection member was explicitly listed in the docs for Model...
I can't get this to work during an initialize call. Any idea how I could make that work?
This through me for a loop too. 'indexOf' is placed under Collections > Underscore Methods in the left hand menu, so it's not out in plain sight.
@Jeffpowrs It's also strange, because indexOf, in the underscore documentation, is an array function, whereas another array function, findIndex, doesn't work with collections.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now