How to avoid events duplication on fullcalendar?

2019-09-04 02:48发布

I'm trying to avoid event duplication on same day using full calendar. I have an event called 'Blocked' and if an specific date already have a Blocked event, not allow the user to add another one.

My problem is, how to get the list of events at specific day on client side?

Here's my code:

$(document).ready(function () {
$('.calendar').fullCalendar({
      dayClick: function (date, jsEvent, view, resourceObj) {
        // Here I would like to check if this date already have a 'Blocked' event, if yes do not need to render another event and make another ajax call.
        var newEvent = {
          title: 'Blocked',
          start: date
        };
        $('.calendar').fullCalendar('renderEvent', newEvent, 'stick');
        $.ajax({
          type: "GET",
          url: "block_date",
          dataType: "json",
          data: {date: date.toJSON()},
          error: function (result) {
            $('.calendar').fullCalendar('removeEvents', newEvent);
          }
        });
      },
      eventClick: function (calEvent, jsEvent, view) {
        if (calEvent.title == 'Blocked') {
          $('.calendar').fullCalendar('removeEvents', calEvent._id);
          $.ajax({
            type: "GET",
            url: "unblock_date",
            dataType: "json",
            data: {date: calEvent.start.toJSON()},
            error: function (result) {
              $('.calendar').fullCalendar('renderEvent', calEvent);
            }
          });
        }
      }
    }
);

});

1条回答
男人必须洒脱
2楼-- · 2019-09-04 03:02

Found a answer to my problem. Not sure if it's the best way to deal with it, but it's working for now.

dayClick: function (date, jsEvent, view) {
        var blockedEvents = $('.calendar').fullCalendar('clientEvents', function (event) {
          return event.title == 'Blocked' && event.start.format() == date.format();
        });
        if (blockedEvents.length < 1) {
          var newEvent = {
            title: 'Blocked',
            start: date
          };
          $('.calendar').fullCalendar('renderEvent', newEvent, 'stick');
          $.ajax({
            type: "GET",
            url: "block_date",
            dataType: "json",
            data: {date: date.toJSON()},
            error: function (result) {
              $('.calendar').fullCalendar('removeEvents', newEvent);
            }
          });
        } else {
          $('.calendar').fullCalendar('removeEvents', blockedEvents[0]._id);
          $.ajax({
            type: "GET",
            url: "unblock_date",
            dataType: "json",
            data: {date: blockedEvents[0].start.toJSON()},
            error: function (result) {
              $('.calendar').fullCalendar('renderEvent', blockedEvents[0]);
            }
          });
        }
      },
查看更多
登录 后发表回答