Search code examples
javascriptecmascript-6fullcalendar-4

How to use a variable inside itself


I want to use the variable inside itself and I see other people do it but why does it not work for me?

This is my ES6 file

// Setup module
// ------------------------------

var FullCalendarAdmin = function () {

    //
    // Setup module components
    //
    var _componentRender = function () {

    // Basic calendar
    var _componentFullCalendarAdmin = function (events) {

        // Define element
        var calendarAgendaViewElement = document.querySelector('.fullcalendar-agenda-admin');

        // Initialize
        if (calendarAgendaViewElement) {
            var calendarAgendaViewInit = new FullCalendar.Calendar(calendarAgendaViewElement, {
                plugins: ['dayGrid', 'timeGrid', 'interaction'],
                select: function (start, end) {
                    var title = prompt("Add event:");
                    var data;
                    if (title != '') {
                        data = {
                            title: title,
                            start: start,
                            end: end
                        };
                        calendarAgendaViewInit.addEvent(data);
                    }
            }).render();

        }
    };

    //
    // Return objects assigned to module
    //

    return {
        init: function () {
            _componentRender();
        }
    }
}();


// Initialize module
// ------------------------------

document.addEventListener('DOMContentLoaded', function () {
    FullCalendarAdmin.init();
});

How can I use the calendarAgendaViewInit to call the addEvent function without getting function as an undefined error?

Thanks in advance!


Solution

  • The problem is that you invoke .render immediately.
    So your calendarAgendaViewInit is not an instance of FullCalendar.Calendar but the result of the render method.
    What you can do is first define the calendarAgendaViewInit variable

    var calendarAgendaViewInit = new FullCalendar.Calendar(calendarAgendaViewElement, {
                    plugins: ['dayGrid', 'timeGrid', 'interaction'],
                    select: function (start, end) {
                        var title = prompt("Add event:");
                        var data;
                        if (title != '') {
                            data = {
                                title: title,
                                start: start,
                                end: end
                            };
                            calendarAgendaViewInit.addEvent(data);
                        }
                });
    

    and then call calendarAgendaViewInit.render().