VB_
VB_

Reputation: 45692

Backbone Collection: custom comparator

I want: to search through Backbone.Collectio by complex criteria. To be more precise, I have startTime & endTime properties of TimePeriod obj, and I want to select TimePeriod to which belongs specific moment.

Example: I have moment equals 12045, and I need to go through collection of timeperiods and check for each:

belongsToTimeperiod: function(timePeriod, moment) {
    return (timePeriod.startTime < moment && timePeriod.endTime > moment);
}

Question: is that possible to make Backbone.Collection use my comparator? How?

Code: [optional]

var TimePeriod = Backbone.Model.extend({
    defaults: {
        'startTime': '',
        'endTime': ''
    },
    validate: function(attrs) {
        if (!startTime) return 'You missed startTime';
        if (!endTime) return 'You missed endTime';
    }
}

And collection of that objects:

var TimePeriods = Backbone.Collection.extend({
    model: TimePeriod
});

Upvotes: 0

Views: 135

Answers (1)

coding_idiot
coding_idiot

Reputation: 13734

var searchTerm=...;
function searchModel(int start, int end){
    var i=(start+end)/2;
       var model=collection.at(i);             //http://backbonejs.org/#Collection-at
       if(model.get('property')>searchTerm){   //Collection is sorted on this 'property'
            return searchModel(start,i);
       }else if(model.getProperty()<searchTerm){
           return searchModel(i,end);
       }
   return model;
}

Untested code, haven't written binary search algo. in a long time. Hope so it gives you an idea.

Upvotes: 1

Related Questions