Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Sortable and Ember.JS

I'm trying to make a sortable list using Ember.JS and this small jQuery + HTML5 plugin. The problem I'm facing is that moving elements in my list is messing up with the METAMORPH system (I think), leading it to strange behaviors.

My solution was to add an event when the order changed and serialize the new order, make a new list out of it and set it as the content of my array. This works, rerendering the whole list, but

  1. rerendering the whole list is heavy
  2. strangely, when sending an action (like clicking a button) it now triggers the action twice, and I have no idea why.

Has anyone recently deal with this situation? I'm aware that there are some questions/answers on this particular subject here, but most of them are totally outdated.

like image 465
Benjamin Netter Avatar asked Apr 29 '26 00:04

Benjamin Netter


1 Answers

Here's what I've done using Sortable from jQueryUi.

App.SortableView = Ember.View.extend({
  didInsertElement : function(){
    $( "#layerList" ).sortable({
      update: function(event, ui) {
        var indexes = {};
        // create a hash of layer ids and positions
        // { idX : pos1, idY : pos2, ...  }
        $(this).find('.layer').each(function(index) {
          // object id is stored in DOM in the data-id attr
          indexes[$(this).data('id')] = index;
        },this);
        // pass the hash to the controller to update the models
        controller.updateSortOrder(indexes);
      }
    });
  }
});

App.SortableController = Ember.ArrayController.extend({
  updateSortOrder: function(indexes) {
    // Let Ember know that things are about to change
    this.propertyWillChange('content');
    var layers = this.get('content');
    // Update each layer with the new position
    layers.forEach(function(item) {
      var index = indexes[item.get('id')];
      item.set('position', index);
    });
    // Let Ember know that changes are finished
    this.propertyDidChange('content');
  }
});

EDIT : I revisited this issue today when trying to nail down some funkiness in one of my apps. I ended up putting together a jsbin that demonstrates this functionality.

http://jsbin.com/EZulAN/1/edit?html,js,output

like image 76
Jeremy Green Avatar answered May 01 '26 12:05

Jeremy Green