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
JavaScript
x
82
82
1
import { Controller} from "stimulus"
2
import { Calendar } from '@fullcalendar/core'
3
import dayGridPlugin from '@fullcalendar/daygrid'
4
import timeGridPlugin from '@fullcalendar/timegrid'
5
import interactionPlugin from '@fullcalendar/interaction'
6
import Rails from '@rails/ujs'
7
8
export default class extends Controller {
9
static targets = ["calendar", "modal", "start_time", "end_time"]
10
11
connect() {
12
let _this = this
13
let calendar = new Calendar(this.calendarTarget, {
14
events: '/admin/events.json',
15
editable: true,
16
selectable: true,
17
navLinks: true,
18
nowIndicator: true,
19
headerToolbar: { center: 'dayGridMonth,timeGridWeek,timeGridDay' },
20
plugins: [dayGridPlugin,timeGridPlugin,interactionPlugin],
21
22
// this navigates to the day selected from month view -> day view
23
navLinkDayClick: function(date, jsEvent) {
24
calendar.changeView('timeGridDay', date);
25
},
26
27
// This method fires when we select a time slot, or range of slots.
28
select: function(info) {
29
30
_this.modalTarget.classList.add('active')
31
_this.start_timeTarget.value = info.start
32
_this.end_timeTarget.value = info.end
33
34
if (info.allDay = true) {
35
_this.allDayTarget.setAttribute('checked', true)
36
}
37
38
},
39
40
eventDrop: function (info) {
41
let data = _this.data(info)
42
Rails.ajax({
43
type: 'PUT',
44
url: info.event.url,
45
data: new URLSearchParams(data).toString()
46
})
47
},
48
49
eventResize: function (info) {
50
let data = _this.data(info)
51
52
Rails.ajax({
53
type: 'Put',
54
url: info.event.url,
55
data: new URLSearchParams(data).toString()
56
})
57
},
58
59
addEvent: function(info) {
60
_this.addEvent( info )
61
}
62
63
})
64
calendar.render()
65
}
66
67
createSuccess(event) {
68
69
this.modalTarget.classList.remove('active')
70
this.addEvent(event)
71
72
}
73
74
75
data(info) {
76
return {
77
"event[start_time]": info.event.start,
78
"event[end_time]": info.event.end,
79
}
80
}
81
}
82
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?
Advertisement
Answer
Move the function outside of the connect() function and you can call it from any function (with a few caveats).
JavaScript
1
14
14
1
connect() {
2
3
this.add_event(info)
4
}
5
6
other_function() {
7
8
this.add_event(info)
9
}
10
11
add_event(info) {
12
13
}
14