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

穿精又带淫゛_ 提交于 2019-12-30 04:16:07

问题


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>');
});

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/19342915/how-to-programmatically-trigger-the-update-callback-of-a-sortable-widget-with-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!