
A fairly common task is to swap items in the list. But as a rule, this problem is solved with eerie crutches, especially if it is Drag & Drop.
Now I will tell you a very simple and flexible way to do this using Marionette.js and jQuery UI Sortable.
Connecting jQuery UI
From jQuery UI we need only a part of Sortable, therefore, to save traffic for the sake of, I boldly removed all unnecessary checkboxes for you
from here . You just need to download.
note
The code below uses the Marionette link.
var Marionette=Backbone.Marionette;
')
Create a pattern of behavior
We implement this functionality in the form of Behavior, which I
wrote about earlier .
Here is the code of behavior that will be responsible for the ability to sort models within the collection.
Behaviors.Sortable=Marionette.Behavior.extend({ onRender:function(){ var collection=this.view.collection
What is it?
This behavior is for CollectionView. He waits for the onRender event, after which he binds each ItemView item to his model using
cid .
Then we allow this list to be sorted using Drag & Drop using jQuery.
Sortable Options
For each type, you can pass your own set of options, for more information, see the
jQuery UI documentation . In the above code, not all possible options are implemented, you can add your own if you wish.
Sorting
When one of the elements is dragged, we remove the model attached to this element by cid from the collection and add it again at the required index. Silent: true flags are needed so that Marionette.js does not try to rearrange everything in its own way, it turns out badly for her.
We connect SollectionView and Behavior
Now apply this in action.
var IView=Marionette.ItemView.extend({
Now you can use the one line behaviors: {Sortable: {}} to add the Drag & Drop sorting feature of CollectionView.
How to save it to the server?
I don’t know in which form the sort order is stored on the server, but using the approach described above, you can transfer the order in any format.
I use MongoDB, so without any problems using sollection.toJSON () I send it to the Node.JS server and save it as is.
You can send an ordered array of id to the server, which you can get with
collection.pluck('id');
That's all
enjoy it works!
I hope the article helped you.
Please write in the comments about what you would like to read more.