ptheofan
ptheofan

Reputation: 2290

Backbone.js using findWhere function to find match based on Date object

I have a model in backbone that has an attribute date that holds an instance of a Date object. I want to search the collection and match the model based on another date object.

i.e.
dt = new Date();
SomeModel = Backbone.Model.extend({date: dt});
someModelCollection.findWhere({date: new Date(dt)});

How can I make it search in a compatible Date comparison manner so that if the date represented by the object matches is matched that model will be returned?

Upvotes: 0

Views: 422

Answers (2)

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

Check this :

var d = new Date('12/12/2012');
// Creating collection
var collection = new Backbone.Collection([
  { d: d }, // One instance with above created date
  { d: new Date()},
  { d: new Date()}
]);
// Filter collection based on above date '12/12/2012'
var filtered = collection.filter(function(c){
    return c.get('d').getTime() == d.getTime();
});
console.log(filtered.length); 
//logs : 1
console.log(filtered[0].get('d')); 
//logs : Date {Wed Dec 12 2012 00:00:00 GMT+0530 (IST)}

Upvotes: 0

Prinzhorn
Prinzhorn

Reputation: 22508

You need to use plain find, because findWhere will in that case just compare references. find also comes closest to a Java comparable/comparator.

var createDateComparator = function(date) {
    return function(model) {
        return +date === +model.get('date');
    };
};

var model = someModelCollection.find(createDateComparator(new Date(dt)));

(untested, but should work)

Upvotes: 1

Related Questions