使用ajax更改事件对象后如何刷新fullcalendar v4

Bou*_*mad 3 javascript ajax jquery fullcalendar fullcalendar-4

我使用 fullcalendar v4 来显示事件。事件正常显示在加载中,但我需要使用多个复选框添加过滤器,并在使用 ajax 更改复选框后刷新 fullcalendar 事件。

更改后我得到新的对象事件,但我需要刷新我尝试calendar.render();但不工作的fullcalendar

fullcalendar V4 !!
Run Code Online (Sandbox Code Playgroud)

全日历脚本

 var taskEvents = JSON.parse($("input[name=tasks_events]").val());
        var calendarEl = document.getElementById('tasks_calendar');
        var  calendar = new FullCalendar.Calendar(calendarEl, {
            locale: 'fr',
            plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek'
            },
            defaultDate: new Date(),
            defaultView: 'timeGridWeek',
            minTime: "09:00:00",
            maxTime: "20:00:00",
            weekends:false,
            businessHours: true, // display business hours
            editable: true,
            selectable: true,
            droppable: true,
            //events:taskEvents ,
            select: function(info) {
                $('#newTaskFormLabel').html('Commence à '+"<b> " + moment(info.startStr).format('DD-MM-YYYY HH:mm') + "</b> "+" fin à " +"<b> " + moment(info.endStr).format('DD-MM-YYYY HH:m:m')) +"</b>"
                $('#newTaskForm').modal('show');
                $('#newTaskForm input[name=start_at]').val(info.startStr);
                $('#newTaskForm input[name=end_at]').val(info.endStr);
            },
            eventClick: function(info) {
                $('#editTaskForm').modal('show');
                console.log(info);
                editTask(info.event);
            },
            // dateClick: function(info) {
            //     alert('clicked ' + info.dateStr);
            // },
            eventResize: function(info) {    
                $('.popover.in').remove();     
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },   
            eventDrop : function(info){
                $('.popover.in').remove(); 
                // $(info.el).removeAttr('aria-describedby');
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },
            eventRender: function(info) {

                $(info.el).append('<img src="'+document.location.origin+'/'+info.event.extendedProps.user_avatar+'" class="img-circle event-avatar" alt="User Image">');
                let state = function (state) { 
                    if(state =="not_started") return "Pas encore commencé";
                    if(state =="started") return "Commencé";
                    if(state =="finish") return "Terminer";
                }
                $(info.el).popover({
                    title: info.event.title,
                    content: function () {
                        let html ="<p>"+moment(info.event.start).format('DD-MM-YYYY HH:mm')+' / '+moment(info.event.end).format('DD-MM-YYYY HH:mm')+"</P>"
                        +"<p>"+info.event.extendedProps.description+"</p>"
                        +"<p>"+"Utilisateur : "+info.event.extendedProps.user+"</p>"
                        +"<p>"+"Projet : "+info.event.extendedProps.project+"</p>"
                        +"<p>"+"Fonction : "+info.event.extendedProps.activity+"</p>"
                        +"<a class='btn btn-primary btn-xs'>"+state(info.event.extendedProps.state)+"</a>";
                        return html;
                    },
                    trigger: 'hover',
                    placement: 'top',
                    html: 'true',
                    container: 'body'
                    });
            },

        });
        calendar.addEventSource( taskEvents );
        calendar.render();
//--------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

ajax脚本

var getTasks = function (data){
            $.ajax({
                url:"/admin/get-users-tasks",
                type:"POST",
                data :{
                    users:data,
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    calendar.addEventSource( response );
                    calendar.refetchEvents();
                },
                error: function(response) {
                    new PNotify({
                        title: "Opération échoué",
                        text: response.message,
                        type: "error"
                      });
                }
              });
        }
Run Code Online (Sandbox Code Playgroud)

关于更改复选框功能

 function onChangeUserCheckbox() {  
        $("input[name*=selected_user]").on('change',function () {
            var selectedUsers = [];
            $.each($("input[name*='selected_user']:checked"), function(){            
                selectedUsers.push($(this).val());
            });
            getTasks(selectedUsers);
            // getTasks(JSON.stringify(selectedUsers));
        })
    }
Run Code Online (Sandbox Code Playgroud)

ADy*_*son 5

您没有准确解释您的代码出了什么问题,但我可以看到,当您从 AJAX 调用获得响应时,您每次都会添加一个新的事件源。我还可以看到,您从未删除任何以前的事件源,因此您只会不断收到越来越多的事件。我将假设这是您要问的问题。

但是,与其一直添加/删除事件源,不如将其声明为可以刷新和更新的单个事件源会更简单。您将使用文档中描述的“事件即函数”模式来声明此源。

这是一些修改后的代码,它会更有意义:

var calendarEl = document.getElementById('tasks_calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
  eventSources: [
    JSON.parse($("input[name=tasks_events]").val()), //static event source
    getTasks //pass a reference to a function, so we have a dynamic, updateable event source
  ]
  ///....all your other options go here as well....
});

$("input[name*=selected_user]").on('change',function () {
  calendar.refetchEvents(); //this will automatically cause the "getTasks" function to run, because it's associated with an event source in the calendar
});

var getTasks = function(fetchInfo, successCallback, failureCallback) { //the input parameters are the ones shown in the fullCalendar documentation
  //find the currently selected users
  var selectedUsers = [];
  $.each($("input[name*='selected_user']:checked"), function(){            
    selectedUsers.push($(this).val());
  });

  //run the ajax call
  $.ajax({
    url: "/admin/get-users-tasks",
    type: "POST",
    data: {
      users: selectedUsers,
    },
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success: function (response) {
      successCallback(response); //pass the event data to fullCalendar via the provided callback function
    },
    error: function(response) {
      new PNotify({
        title: "Opération échoué",
        text: response.message,
        type: "error"
      });

      failureCallback(response); //inform fullCalendar of the error via the provided callback function
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

1) 在此版本中,当日历加载时,它会立即向服务器发出 AJAX 请求并尝试获取事件。但是,由于没有选中复选框,因此不会将数据传递到服务器。我不知道您的服务器代码当前在这种情况下做什么,或者您希望它做什么。我想它应该返回所有可能的事件,或者根本不返回。无论哪种方式,您都需要确保设置服务器代码来处理这种情况并返回任何有意义的数据。

2)我在这里也添加了您的其他事件集(取自您的隐藏字段)作为事件源。无需通过“addEventSource”单独添加它,因为您在日历加载时立即添加它 - 您可以改为在选项中声明它。

3)我没有使用提供的 fetchInfo数据在这里,但理想情况下,您应该从该对象中获取开始和结束日期值并将它们作为参数发送到您的服务器,并且您的服务器应该使用它们来过滤数据并且只返回开始日期介于这两个日期之间的事件. 这将更有效率,因为这样您将只返回实际将显示在日历上的数据,而不是用户曾经拥有的所有任务 - 如果您考虑一下,一旦您的应用程序使用了一段时间几个月后,他们将开始拥有大量过去的数据,没有必要每次都下载这些数据,因为几乎可以肯定这些数据不会被查看。(请注意,如果用户确实导航到过去/未来日期并且 fullCalendar 没有这些日期的事件数据,它将再次运行 AJAX 调用并要求服务器提供它。

有关在日历选项中配置事件源的文档,请参阅https://fullcalendar.io/docs/eventSources