How to programmatically trigger a callback to update a sortable widget using a button?

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

for example, if the user clicks the add button, I want to know what event is fired and do something in the event. for example, when updating fire, I do something in the sortable update method

 $('.sort').sortable({ update:function(){ //if update fire do some thing } }); $('#add').click(function(){ $('.sort').append('<li>Text</li>'); }); 
+8
jquery jquery-ui jquery-ui-sortable
source share
2 answers

Problem

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

Decision

If you want to trigger an event manually, you also need to bind it manually. Please note that the event will also be triggered automatically using the regular behavior of widgets (for example, a user sorting elements in a 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

+15
source share

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

Since the update callback is defined as an option of the sortable widget, it can be obtained as such by calling the method:

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

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

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

Working JS script

+15
source share

All Articles