I have Backbone collection that consists of models that have the following attributes:
{
startTime: Date('...'),
endTime: Date('...')
}
When I add a new model I have to check that there is no dates intersections between added and exists ones.
So for example:
var startTime = new Date();
var endTime = new Date(new Date().setHours(1));
if (!this.collection.check({startTime: startTime, endTime })) {
this.create({startTime: startTime, endTime });
}
What's the best way to do this?
You could test every model in your collection to check if the future dates do not overlap with an existing interval. For example, and with a condition based on the answers in 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));
});
}
});
And a demo http://jsfiddle.net/nikoshr/eaF5z/2/
Or if you prefer a more explicit version
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);
});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.