如何以编程方式触发带有按钮的可排序小部件的更新回调?
根据此 jsbin ,我有一个sortable
列表和一个按钮.当单击按钮时,将某些内容添加到sortable
中,并且我想知道触发了sortable
的哪个事件?(更新,接收),并且在找到该事件时对该事件执行某些操作.
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.
例如,如果用户单击add
按钮,我想知道触发了哪个事件并在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>');
});
问题
当您将update
回调定义为sortable
小部件选项的一部分时,称为sortupdate
的事件被 not 绑定到该小部件.换句话说,确实调用了update
选项定义的回调函数,但是在这种情况下不会触发具有该名称的事件.
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.
解决方案
如果您希望手动触发该事件,则还需要手动绑定.请注意,该事件还将由小部件的正常行为(例如,用户对小部件中的元素进行排序)自动触发.
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).
例如:
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
});