Change Fullcalendar event source after render

There are some methods called removeEventSource() and addEventSource() that allow you to tweak the sources list. I had a similar situation where I needed to hide one of the sources in month view, but show it in other contexts, and I found removing and re-adding elements in the eventSources array the cleanest way to achieve this.

    var fcSources = {
        courses: {
                    url: base+'accessfm/calendar/courses',
                    type: 'GET',
                    cache: true,
                    error: function() { alert('something broke with courses...'); },
                    color: 'purple',
                    textColor: 'white',
                    className: 'course'
                },
        requests: {
                    url: base+'accessfm/calendar/requests',
                    type: 'GET',
                    cache: true,
                    error: function() { alert('something broke with requests...'); },
                    textColor: 'white',
                    className: 'requests'
                },
        loads:  {
                    url: base+'accessfm/calendar/loads',
                    type: 'GET',
                    cache: true,
                    error: function() { alert('something broke with loads...'); },
                    color: 'blue',
                    textColor: 'white',
                    className: 'loads'
                }
    };
<snip>
    $('#fullcalendar').fullCalendar({
        header: {
                    left: 'title',
                    center: 'agendaDay,agendaWeek,month',
                    right: 'today prev,next'
                },
        defaultView: 'agendaWeek',
        firstDay: 1,
        theme: true,
        eventSources: [ fcSources.courses, fcSources.requests, fcSources.loads ],
        viewDisplay: function(view) {
            if (lastView != view.name){ // view has been changed, tweak settings
                if (view.name == 'month'){
                    $('#fullcalendar').fullCalendar( 'removeEventSource', fcSources.loads )
                                      .fullCalendar( 'refetchEvents' );;
                }
                if (view.name != 'month' && lastView == 'month'){
                    $('#fullcalendar').fullCalendar( 'addEventSource', fcSources.loads );
                }
            }
            lastView = view.name;
        }
    });

Don’t just copy/paste this code, because it’s not solving exactly your problem. But you should be able to take some ideas from it. Tweak the fcSources hash to suit your sources, and then instantiate your fullCalendar object with just one of the sources, and swap it around using the removeEventSource and addEventSource methods.

Note also the use of refetchEvents() – that’s necessary to make sure the display is rerendered correctly.

Leave a Comment