我有Backbone集合,它由具有以下属性的模型组成:
{
startTime: Date('...'),
endTime: Date('...')
}
当我添加新模型时,我必须检查添加和存在之间没有日期交叉点。
例如:
var startTime = new Date();
var endTime = new Date(new Date().setHours(1));
if (!this.collection.check({startTime: startTime, endTime })) {
this.create({startTime: startTime, endTime });
}
最好的方法是什么?
答案 0 :(得分:2)
您可以测试集合中的每个模型,以检查未来日期是否与现有间隔重叠。例如,并且条件基于JavaScript date range between date range中的答案,
var C = Backbone.Collection.extend({
check: function(opts) {
// returns true if the given interval overlaps with any model
var start = opts.startTime,
end = opts.endTime;
return this.any(function(model) {
// returns true if the given interval overlaps
return !((model.get('startTime')>=end) || (model.get('endTime')<=start));
});
}
});
演示http://jsfiddle.net/nikoshr/eaF5z/2/
或者如果您更喜欢更明确的版本
var C = Backbone.Collection.extend({
check: function(opts) {
var startdate = opts.startTime,
enddate = opts.endTime;
return this.any(function(model) {
var startD = model.get('startTime'),
endD = model.get('endTime');
return (startD >= startdate && startD <= enddate) ||
(startdate >= startD && startdate <= endD);
});
}
});