0

I have a sortable list (I didn't use jqueryui sortable, I wrote a small one all by myself) in Backbone.js app. For every list item, it's Backbone model has an order attribute which keeps its order in the list. Every time I sort this list, I want to change this order attribute for every list item that has changed position. But the problem is, I don't know how to detect the sort action. Maybe it's easy to detect this action in the item model that is being dragged, but as other items' positions will be affected as this item moves, how to detect the sort action in these item models and subsequently, change the order attribute of them?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
chaonextdoor
  • 5,019
  • 15
  • 44
  • 61
  • 2
    You wrote the sorting code..... wouldn't you be the only one to answer this question? – asawyer May 03 '12 at 22:29
  • @asawyer But my sorting code is just about changing the view. It has nothing to do with the model. So what I want to know is how to change the corresponding model's attribute as the view changes. – chaonextdoor May 03 '12 at 22:35
  • 1
    @chaonextdoor the View just always reflects the changes to model. Controller should actually change the model's attributes.( here events from the view). btw `I didn't use jqueryui sortable, I wrote a small one all by myself` and ` But the problem is, I don't know how to detect the sort action` you totally contradict what you say. Either the sorting plugin is not complete or you don't have much knowledge on what happens in sorting plugin – Deeptechtons May 04 '12 at 12:18

1 Answers1

0

When you change the position of an item in the list (by dragging, or however), does an event fire that you can bind to? If nothing else, if you're dragging them perhaps you could bind to mouseup. Are the models in a collection? Or can you get to your Backbone view objects from the DOM elements?

Perhaps something like this. This assumes that you've stored the Backbone view object in a view_object property using jQuery.data, and that you've passed the corresponding model to the view constructor as the model property of the options object.

var Item_View = Backbone.View.extend( {

  initialize : function ( options ) {

    this.$el.data( 'view_object', this );

  },

  events : {

    "mouseup" : function () {

      $( "#items .item" ).each( function ( index ) {

        $( this ).data( 'view_object' ).model.set( 'order', index );

      } );

    }
    // "mouseup"

  }
  // events

} );


var model = new Item_Model( {} );

var view = new Item_View( {

  model : model

} );
JMM
  • 26,019
  • 3
  • 50
  • 55