Im still learning stimulus.js and I'm trying to expand on the DriftingRuby episode on stimulusJS and FullCalendar. In that tutorial the form submits a normal http put request and the page is reloaded. I'd like to allow users to manage events using UJS/Stimulus and not requiring a page reload.
This is my 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,
}
}
}
I need to call the add_event
method inside connect() lifecycle callback. As I'm learning Stimulus.js Im having a hard time finding examples where someone is trying to do something similar.
Is it possible to call the add_event
method from outside the connect() method?
Move the function outside of the connect() function and you can call it from any function (with a few caveats).
connect() {
...
this.add_event(info)
}
other_function() {
...
this.add_event(info)
}
add_event(info) {
...
}