1

我还在学习stimulus.js,我正在尝试扩展关于stimulusJS 和FullCalendar 的DriftingRuby 集。在该教程中,表单提交了一个普通的 http put 请求并重新加载了页面。我想允许用户使用 UJS/Stimulus 管理事件,而不需要重新加载页面。

这是我的 calendar_controller.js

import { Controller} from "stimulus"
import { Calendar } from '@fullcalendar/core'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import Rails from '@rails/ujs'

export default class extends Controller {
    static targets = ["calendar", "modal", "start_time", "end_time"]

    connect() {
        let _this = this
        let calendar = new Calendar(this.calendarTarget, {
            events: '/admin/events.json',
            editable: true,
            selectable: true,
            navLinks: true,
            nowIndicator: true,
            headerToolbar: { center: 'dayGridMonth,timeGridWeek,timeGridDay' },
            plugins: [dayGridPlugin,timeGridPlugin,interactionPlugin],

            // this navigates to the day selected from month view -> day view
            navLinkDayClick: function(date, jsEvent) {
                calendar.changeView('timeGridDay', date);
            },

            // This method fires when we select a time slot, or range of slots.
            select: function(info) {

                _this.modalTarget.classList.add('active')
                _this.start_timeTarget.value = info.start
                _this.end_timeTarget.value = info.end
                
                if (info.allDay = true) {
                    _this.allDayTarget.setAttribute('checked', true)
                }

            },

            eventDrop: function (info) {
                let data = _this.data(info)
                Rails.ajax({
                    type: 'PUT',
                    url: info.event.url,
                    data: new URLSearchParams(data).toString()
                })
            },

            eventResize: function (info) {
                let data = _this.data(info)

                Rails.ajax({
                    type: 'Put',
                    url: info.event.url,
                    data: new URLSearchParams(data).toString()
                })
            },

            addEvent: function(info) {
                _this.addEvent( info )
            }
            
        })
        calendar.render()
    }

    createSuccess(event) {

        this.modalTarget.classList.remove('active')
        this.addEvent(event)

    }


    data(info) {
        return {
            "event[start_time]": info.event.start,
            "event[end_time]": info.event.end,
        }
    }
}

我需要add_event在 connect() 生命周期回调中调用该方法。当我学习 Stimulus.js 时,我很难找到有人试图做类似事情的例子。

是否可以从 connect() 方法外部调用该add_event方法?

4

1 回答 1

2

将函数移到 connect() 函数之外,您可以从任何函数调用它(有一些注意事项)。

connect() {
  ...
  this.add_event(info)
}

other_function() {
  ...
  this.add_event(info)
}

add_event(info) {
  ...
}
于 2021-03-09T11:49:58.433 回答