Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Yarn/NPM package #45

Open
bpsimao opened this issue Dec 3, 2019 · 5 comments
Open

Create Yarn/NPM package #45

bpsimao opened this issue Dec 3, 2019 · 5 comments

Comments

@bpsimao
Copy link

bpsimao commented Dec 3, 2019

Case: Rails 6 with webpack

@mybuddyandrew
Copy link

How do I install?

@itmammoth
Copy link
Owner

I think it's time to make independence from jQuery...

@denny
Copy link

denny commented Sep 12, 2020

I'm also trying to install into a rails6+webpacker project, and failing miserably. JavaScript is not my strong point (and webpacker seems to have made it 10x as confusing so far) so I have no idea whether I'm failing because I'm missing something, or because its not actually possible currently... clues welcome! 🙂

@sergio-rivas
Copy link

You do this in ES6 by custom setting up this package with custom configuration on change.
https://github.com/SortableJS/Sortable

Then you need to do post request to '/sortable/reorder', and give the following params:

// pass array of sortable_id's from table in new order
{ rails_sortable: [ sortable_id, ... ] }

@TheBrockEllis
Copy link

To add a bit more context to sergio-rivas's answer from above, this is how I accomplished using this Gem with Rails 6 and webpacker.

javascript

import Sortable from 'sortablejs';

var sortables = document.querySelector('#sortable');
Sortable.create(sortable, {
      draggable: '.list-group-item',
      dataIdAttr: 'data-sortable-id',
      
      onUpdate: function (event) {
        const listItems = event.target.querySelectorAll('.list-group-item');
        const sortableIds = Array.from(listItems).map(elm => elm.dataset.sortableId)
        $.post('/sortable/reorder', { rails_sortable: sortableIds })
      }
});

html.erb

<ul class="sortable">
    <li class="list-group-item" data-sortable-id="<%= item.sortable_id %>">
 ...

Using the onUpdate from the Sortable library, we can hook into when the drag-n-drop has ended. I used the event object to find all of the list-group-item elements within the parent and map over them to get their sortable Ids. Then a quick post request to the /sortable/reorder endpoint.

I did have troubles with the CSRF tokens and ended up disabling enforcement for the reorder endpoint with an initializer as described here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants