Joran Den Houting Joran Den Houting - 5 months ago 39
jQuery Question

How to manually trigger 'update' in ui-sortable

I'm using an UI sortable with in each item a

delete
button. Here is the delete function:

$('.delete_item').click(function(){
$(this).closest('.grid_3_b').remove();
initSortable();
$(".sortable").sortable('refresh').trigger('update');
});


The
div
get's removed as I want to, but there is no
update
data sent to PHP.. So my script won't save the order and deleted item..

Here is my
initSortable();
function:

function initSortable() {
$( ".sortable" ).sortable({
items: '.grid_3_b, .dropable',
connectWith: ".sortable",
placeholder: "placeholder",
remove: function(event, ui) {
if(!$('div', this).length) {
$(this).next('.dropable').remove();
$(this).remove();
}
initMenu();
},
receive: function(event, ui) {
if( $(this).hasClass( "dropable" ) ) {
if( $(this).hasClass( "gallery__item--active" ) ) {
$(this).before( "<div class=\"dropable gallery__item sortable\"></div>" );
$(this).after( "<div class=\"dropable gallery__item sortable\"></div>" );

initSortable();
$(".sortable").sortable('refresh').trigger('update');
initMenu();
}
}
},
update : function () {
var neworder = new Array();
$('.sortable').each(function() {
var id = $(this).attr("id");
var pusharray = new Array();
$('#' + id).children('div').each(function () {
var art = $(this).attr("data-art");
var pos = $(this).attr("data-pos");
pusharray.push( {data:{'art':art, 'pos':pos}} );
});
neworder.push({'id':id, 'articles':pusharray});
});

$.post("example.php",{'neworder': neworder},function(data){});
initMenu();
}
}).disableSelection();
}

initSortable();


Also, the
remove
function normally deletes a column when it's empty, but doesn't work when deleted the latest item in the column.. Is this because the update trigger isn't called?

T J T J
Answer

For manually triggering events in jquery-ui sortable, instead of specifying the handler in options object, you need to bind the event handler after sortable initialization.

For example the following will not work

$('ul').sortable({
  update: function () {
    console.log('update called');
  }
});
$('ul').trigger('sortupdate'); // doesn't work

Following works

$('ul').sortable();
$('ul').on('sortupdate',function(){
   console.log('update called');
});
$('ul').trigger('sortupdate'); // logs update called.

Demo

Comments