如何替换FullCalendar库中的所有事件

时间:2019-04-26 01:45:49

标签: javascript fullcalendar

我正在使用FullCalendar.io库创建一个页面,以在网页上显示事件。

现在,当用户在日期范围之间导航时,我想动态加载事件。使用文档,我可以在用户按下“下一步”按钮时添加新事件,但是它只是将事件追加到现有事件对象上,我想做的是删除所有现有事件并仅显示新列表。我该怎么办?

您可以查看功能here on my CodePen

HTML

  <p>
    <button id='prev'>prev</button>
    <button id='next'>next</button>
  </p>
<div id='calendar'></div>

JS

var calendar;
var eventsList = [{
  id: '1',
  title: 'event 1',
  start: '2019-04-06'
},
                  {
                    id: '2',
                    title: 'event 2',
                    start: '2019-04-07'
                  },
                  {
                    id: '3',
                    title: 'event 3',
                    start: '2019-04-29'
                  },
                  {
                    id: '4',
                    title: 'event 4',
                    start: '2019-04-30'
                  }];

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');

  calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
    timeZone: 'UTC',
    defaultView: 'dayGridMonth',
    header: {
      left: '',
      center: 'title',
      right: ''
    },
    editable: true,
    events: eventsList

  });

  calendar.render(); 

});

document.getElementById('prev').addEventListener('click', function() {
  calendar.prev(); // call method
});

document.getElementById('next').addEventListener('click', function() {

  // replace existing list - this will doneby another function, hard coding for demo
  eventsList = [{
    id: '5',
    title: 'event 5',
    start: '2019-05-06'
  },
                {
                  id: '6',
                  title: 'event 6',
                  start: '2019-05-07'
                },
                {
                  id: '7',
                  title: 'event 7',
                  start: '2019-05-08'
                },
                {
                  id: '8',
                  title: 'event 7',
                  start: '2019-05-09'
                }];
  calendar.next(); // call method
  calendar.addEventSource(eventsList);
  //calendar.refetchEvents(); // using this instead of the line above does not work either, just loads original list
});

1 个答案:

答案 0 :(得分:0)

我误读了文档,getEventSource返回了一个eventSource数组,因此只需指向索引然后删除即可。

  calendar.getEventSources()[0].remove();

或者如果您有多个资源,

  calendar.getEventSources().forEach(eventSource => {
    eventSource.remove()
  })

下面的代码有误,请留作记录。

在添加事件源之前如何添加remove()

  calendar.next(); // call method
  calendar.getEventSources().remove();
  calendar.addEventSource(eventsList);
  //calendar.refetchEvents(); // this does not work either, just loads original list

https://fullcalendar.io/docs/Calendar-getEventSources
https://fullcalendar.io/docs/EventSource-remove