Search code examples
jqueryfullcalendarfullcalendar-scheduler

Preventing Fullcalendar of adding a new click event handler for the same element when month is changed


I have a click event handler in EventAfterAllRender callback and I don´t know the reason but every time I change the month in timelineMonth, a new click handler is added to the same element, triggering as many times as handlers have been added when I click the element.

How can I avoid this? I thought of placing click handler code outside fullCalendar but I need it fires in timelineMonth view. I need to limit one click handler per element.

$(function() { // document ready

  $('#calendar').fullCalendar({
    schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
    editable: true,
    navLinks: true,
    header: {
      left: 'today prev,next',
      center: 'title',
      right: 'timelineDay,timelineMonth'
    },
    defaultView: 'timelineMonth',
    // This handler is added as many times as I change the month
    // and I need to prevent this
    eventAfterAllRender: function(view) {

        $("td.fc-resource-area tr").on('click', function(e) {
                alert ("Hi!")      
      });   
    },

    resourceGroupField: 'building',
    resourceColumns: [
        {
            labelText: 'first column',
            field: 'title',
            width: 150
        }
    ],
    resources: [{
      id: 'a',
      building: '460 Bryant',
      title: 'Click here',
      title2: 'Auditorium A\nAddition info'
    }, {
      id: 'b',
      building: '460 Bryant',
      title: 'Click here',
      eventColor: 'green'
    }, {
      id: 'c',
      building: '460 Bryant',
      title: 'Click here',
      eventColor: 'orange'
    }],
    events: [{
      id: '1',
      resourceId: 'b',
      start: '2016-12-07T02:00:00',
      end: '2016-12-07T07:00:00',
      title: 'event 1'
    }, {
      id: '2',
      resourceId: 'c',
      start: '2016-12-07T05:00:00',
      end: '2016-12-07T22:00:00',
      title: 'event 2'
    }, {
      id: '3',
      resourceId: 'f',
      start: '2016-12-07T00:30:00',
      end: '2016-12-07T02:30:00',
      title: 'event 5'
    }]
  });

});

JSFiddle


Solution

  • A new click handler is added because you can add an infinite number of event handlers to an element - adding a new one doesn't remove the old ones. And of course every time you change the date it re-renders the events, but it doesn't re-render the resources, so more handlers just get added to the existing resource elements.

    You can solve it using .off() to remove all previous event handlers on the selected elements i.e.

    $("td.fc-resource-area tr").off().on('click', function(e) { alert ("Hi!") });
    

    Update to your JSFiddle: https://jsfiddle.net/xvos6f82/6/