Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically trigger the update callback of a sortable widget with a button?

According to this jsbin i have a sortable list and a button . when click on button something add to sortable and i want to know which event of sortable is fired?(update,receive) and when finding the event do something on that event.

for example if user click on add button i want to know which event is fired and doing something on event . for example if update fire i do some thing in update method of sortable

$('.sort').sortable({
 update:function(){
//if update fire do some thing
}
});
  $('#add').click(function(){
  $('.sort').append('<li>Text</li>');
});
like image 269
MBehtemam Avatar asked Oct 13 '13 07:10

MBehtemam


2 Answers

The Problem

When you define the update callback as part of the sortable widget options, an event called sortupdate is not bound to the widget. In other words, the callback function defined by the update option is indeed called, but an event by that name is not triggered in this situation.

The solution

If you wish to trigger the event manually, you also need to bind it manually. Note the event will also be triggered automatically by the widget's regular behavior (e.g. a user sorting the elements in the widget).

For example:

HTML

<ul class="sort"></ul>
<button id="add">Add</button>

JS

 // Instantiate the widget
$('.sort').sortable();

 // Bind the update event manually
$('.sort').on('sortupdate',function() {console.log('update')});

$('#add').click(function(){
    $('.sort').trigger('sortupdate'); // Trigger the update event manually
});

See JS Bin Demo

like image 186
Boaz Avatar answered Nov 07 '22 15:11

Boaz


Use the option method from the sortable (to retrieve its callbacks)

As the update callback is defined as an option of the sortable widget it can be retrieved as such by calling the option method:

$('.sort').sortable('option', 'update');

The update callback expects two parameters, the event and a ui object. The event can be set to null and the ui object needs to be defined with all the properties your update callback expects:

$('#add').click(function() {
    $('.sort').sortable('option','update')(null, {
        item: $('<li>new item</li>').appendTo($('.sort'))
    });
});

Working JS-Fiddle

like image 22
flu Avatar answered Nov 07 '22 14:11

flu