我在骨干网中有一个模型,它具有一个包含Date对象实例的属性日期。我想搜索集合并根据另一个日期对象匹配模型。
i.e.
dt = new Date();
SomeModel = Backbone.Model.extend({date: dt});
someModelCollection.findWhere({date: new Date(dt)});
如何以兼容的日期比较方式进行搜索,以便在对象所代表的日期匹配时匹配该模型?
答案 0 :(得分:1)
您需要使用普通find
,因为在这种情况下findWhere
只会比较引用。 find
也最接近Java比较/比较器。
var createDateComparator = function(date) {
return function(model) {
return +date === +model.get('date');
};
};
var model = someModelCollection.find(createDateComparator(new Date(dt)));
(未经测试,但应该有效)
答案 1 :(得分:0)
检查一下:
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)}