Inoperable
Inoperable

Reputation: 1509

Backbone Collection search through models attribute - done properly

I have this nifty function that traverse through models in the collection for a attribute and value. If it finds the value it returns true.

After looking through a lot of doc's, I'm still a bit confused on how to traverse the collection properly and how to search through it. Since underscorejs (in my case lodash) is hooked into backbone I do traverse the collection with .each

I didn't put an else after if (model.get(attribute)===value) because it would return false before traversing through the whole collection. A callback function sounds like unnecessary complication - but maybe i'm wrong (I started with JS few months ago)

I'll be glad for tips and/or a nicer solution ;-) with an explonation. Thanks in advance.

I use requirejs, that why I do pass the _,Bacbkone...

Here is how the Collection looks like:

function (_, Backbone, AppModels) {

    var QueriesCollection = Backbone.Collection.extend({
        model : AppModels.QueryModel,

        search: function (attribute, value) {
            var found = false;
            this.each(function (model) {
                if (model.get(attribute)===value) {
                    found = true;
                }
            });
            return found;
        }
    });

    return {
        QueriesCollection: QueriesCollection
    };
});

Upvotes: 1

Views: 3544

Answers (1)

McGarnagle
McGarnagle

Reputation: 102763

You could also use the Underscore some (aka any), which is almost the same as your search function, except it takes a function argument to use as its predicate, instead of a key/value:

Returns true if any of the values in the list pass the iterator truth test. Short-circuits and stops traversing the list if a true element is found.

The implementation use this is a bit more direct:

search: function (attribute, value) {
    return this.some(function(x) { 
        return x.get(attribute) === value; 
    });
}

Upvotes: 6

Related Questions