Hello Stimulus users,
I try to use Sortablejs with stimulus + Rails backend.
this is my prototype.
when drag and drop end, I use ajax with Rails.ajax in stimulus controller.
sortable = Sortable.create(this.collectionListTarget, {
handle: ".drag-handle",
animation: 150,
swap: true,
onEnd: (/**Event*/evt) => {
var itemEl = evt.item; // dragged HTMLElement
console.log('on End')
console.log(evt)
console.log(ctrlThis.collectionListTarget)
const data = 'collection[title]=UJS 테스트'
Rails.ajax({
url: "/collections",
type: "post",
contentType: 'html',
data,
success: function(data) {
const event = [null, null, { response: data }]
return true
},
error: function(data) {
console.error('error => ', data)
}
})
}
})
create collection is for testing. ajax call is always succeed. but I don’t know where to set action for sort.
<div data-controller="collections">
<button data-action="click->collections#toggle" data-target="collections.toggler">
create new collection
</button>
<%= form_with(
model: Collection.new,
data: { type: "html", target: "collections.form", action: "ajax:success->collections#onAddCollection ajax:error->collections#onAddCollectionError"},
class: "d-none"
) do |form|
%>
<div>
<%= form.text_field :title, data: { target: "collections.input" } %>
</div>
<input type="submit" value="Submit">
<% end %>
<ul id="collections" class="list-unstyled" data-target="collections.collectionList">
<%= render @collections %>
</ul>
</div>
where is the right place for stimulus action? I don’t know where to set ajax:sucess handler.
document.body.addEventListener('ajax:success', function(event) {
})
this event listener only works when form action success.
I use custom action with Rails.fire, it works well. But I did not know it is best practice.