问题描述
我仍在学习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',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,}
}
}
我需要在 connect() 生命周期回调中调用 add_event
方法。在我学习 Stimulus.js 时,我很难找到有人试图做类似事情的例子。
是否可以从 connect() 方法外部调用 add_event
方法?
解决方法
将函数移到 connect() 函数之外,您可以从任何函数调用它(有一些注意事项)。
connect() {
...
this.add_event(info)
}
other_function() {
...
this.add_event(info)
}
add_event(info) {
...
}