Suppose there is a User model with the attributes id and name . The model is in the UserList collection.

I want to quickly get a model from a collection whose name is "Jhony" or null instead, if there is no such model. How can I do it?

As an exit, you can, of course, search through the underscore functions map , detect , select . But it seems very piled up.

  • one
    <pre> var Jhony = UserList.filter (function (user) {return user.get ("name") === Jhony;}); </ pre> According to Backbone Collection - Specter
  • filter is alice select It is also possible that in Jhony there will be []. - rnd_d
  • one
    Well, yes, but I don’t know the “faster” way =) - Specter

2 answers 2

If you need to receive quickly , and there are a lot of models (ie, O(n) does not suit), but, at the same time, the field values ​​are small and you can donate memory - you can build indices.

For example, by making an auxiliary class something like this:

 class IndexedCollection extends Backbone.Collection index_by: [] initialize: -> @_indexes = {by_key: {}, by_id: {}} super _onModelEvent: (ev, model, collection, options) -> retval = super(ev, model, collection, options) id = model.id for k in @index_by v = model.get(k) @_indexes.by_key[k] ?= {} @_indexes.by_key[k][v] ?= [] @_indexes.by_id[k] ?= {} prev = @_indexes.by_id[k][id] if prev? and prev != v @_indexes.by_key[k][prev] = _.without @_indexes.by_key[k][prev], id @_indexes.by_id[k][id] = v switch ev when "add", "change" then @_indexes.by_key[k][v] = _.union @_indexes.by_key[k][v], [id] when "remove" then @_indexes.by_key[k][v] = _.without @_indexes.by_key[k][v], id retval getByIndex:(key, value) -> for id in @_indexes.by_key[key]?[value] ? [] @.get(id) 

The code is an improvisation, sketch and prototype, not very optimized and tested.

And, yes, sorry for CoffeeScript, I hope the difference does not matter - on JS to write something lazy.

  • 2
    Not sorry for coffeScript! When I saw the code, I immediately realized that I had missed something and had not previously paid attention to CoffeScript. Thank you so much for the idea with the indexes and for the new language. I now understand your laziness to write on js. - rnd_d
  • one
    BackBone.js way, CoffeeScript and BackBone.js creations of the same programmer =) - Specter
  • cool! index on the client! - Vlad Lisovsky

Apparently there is no simpler way, in the end I made myself a method for the collection, which would not be so cumbersome, can someone help:

 getByAttr: function(attr, value){ return this.detect( function(model){ return model.get(attr) == value; }); },