1

I'm trying to get a backbone.js view to listen for an event from jquery-ui sortable. The update event is triggered when the user stopped sorting and the DOM position has changed.

Here's what my view looks like:

var ProductListView = Backbone.View.extend({

    el: '#products',

    initialize: function(){
            _.bindAll(this, 'render','addOne', 'sortChanged');

            this.listenTo(app.collection.filteredProducts, 'reset', this.render);
            this.listenTo(this.$el, 'update', this.sortChanged);

            this.$el.sortable();

    },

    render: function(){

            this.$el.html('');

            this.collection.each(function(product){
                    this.addOne(product);
            }, this);

            return this;
    },

    addOne: function(product){
            var view = new ProductItemView({model: product});
            this.$el.append(view.render().el);
    },

    sortChanged: function(){
            alert('changed');
    }

});

I thought that this.$el would emit an update event since that is the same element sortable is applied to. However, I'm not getting any alerts after adjusting the sort of the list, so it seems like the event is not being fired the way I would have expected.

I have read this post:

Saving jQuery UI Sortable's order to Backbone.js Collection

That method seems to work, but I would like to understand why this method does not.

Community
  • 1
  • 1
flyingL123
  • 7,686
  • 11
  • 66
  • 135

1 Answers1

3

Try using the views events.

var ProductListView = Backbone.View.extend({
    el: '#products',
    events: {
        sortupdate: 'sortChanged'
    },
    ...
});

According to the jQueryUI documentation, the event name is actually, "sortupdate". You can add the listener one of two ways.

Code examples:

Initialize the sortable with the update callback specified:

$( ".selector" ).sortable({
  update: function( event, ui ) {}
});

Bind an event listener to the sortupdate event:

$( ".selector" ).on( "sortupdate", function( event, ui ) {} );
Brian Lewis
  • 5,739
  • 1
  • 21
  • 28