7

I have a backbone.js project I have been working on, and I have it setup so that I can drag and drop rows (which are backbone.js models) and with the help of the jQuery UI update event I am able to make my models re-figure their order and everything is well. I was wondering if anyone new a cleaner way to make this happen. I have included some code below.

$( ".section" ).sortable({items: 'tr', update: function()
{
    console.log("Event Fire!");
    secv.mySort();
}});

secv is my View for the model that holds the table. The mySort function goes through and figures out the order of the elements and does the necessary updating.

Jason
  • 1,114
  • 1
  • 10
  • 24
  • what do you not like about this solution? I think it works fairly well without a whole lot of code. This is how I have sortables implemented with backbone right now as well. – c3rin Jul 05 '11 at 21:42
  • Another option which is more complicated is here: http://stackoverflow.com/questions/10147969/saving-jquery-ui-sortables-order-to-backbone-js-collection – Cymen Aug 29 '12 at 21:11

1 Answers1

1

I'm presuming you are setting the collection property in the View perhaps in the initialize method. In that same method, you should bind a view method to the collection's 'change' or 'refresh' event. This method would simply redraw the sorted collection; sorting the collection prior to doing so if necessary.

In theory, your model would have potentially updated itself with its new position and if the collection has a comparator function, the collection would automatically resort itself. If this is the case, binding to the 'refresh' event of the collection would trigger the above-mentioned method which needs only to re-render the collection portion of the view.

Bill Eisenhauer
  • 6,183
  • 2
  • 30
  • 28
  • And also you can assign new comparator to collection before sorting. `collection.comparator(function(model){return model.get('some_property');}); collection.sort();` It will fire collections _reset_ event, which you can bind to rendering collection view. – Ivan Ivanic Jul 06 '11 at 08:43
  • 3
    How does this answer the original question? The problem is that the view (DOM) is arranged before the model collection, not the other way around. – Attila Kun Jun 24 '12 at 18:10