如何使用jQuery排序等待和更新



我使用sortable的接收从拖动列表中接收元素。发生这种情况时,元素的数据将使用AJAX调用发送到服务器,并在数据库中创建一个条目。完成后,将返回ID并添加到新元素中。

我还具有同一可排序列表的 update 函数,在任何更改后,它遍布列表以获取ID,并进行另一个用于更新值的AJAX调用。

问题是混合了过程,更新功能在加载新元素的ID之前抓住了所有ID,这意味着它将缺少新元素的ID。

$( ".sort1" ).sortable({
    connectWith: ".sortable-sections",
    stack: ".sortable-sections ul",
    cancel: "input,textarea,button,select,option,[contenteditable],.editorArea,.unsortable",
    receive: function(event, ui) {
        // lots of things happen
        createNewComponentInDB(data); 
        // leads to the ajax post which if successful $(newItem).attr('id', response); 
    },
    update: function(event, ui) {
        // grab list items indexes and ids
        // ajax post to update in database
    }

在转到"更新"中的函数之前,我该怎么做才能使"接收"中的功能完成?还是有更好的方法可以做到这一点?

编辑:

样本html:

<ul class="space-sections sortable-sections sort1 ui-sortable"> 
    <li class="space-section drag draggable-item ui-sortable-handle" id="5c920e65a7917045fbf62d45" data-component-type="list"> 
    /* ... lots of nested stuff */
    </li>
    <li class="space-section drag draggable-item ui-sortable-handle" id="5c920e6ca7917045fbf62d46" data-component-type="list"> 
    /* ... lots of nested stuff */
    </li>
</ul>

使用解决方案更新:

多亏了与 @elem4th的对话,我能够使用"标志概念"来解决此问题。

  1. 我创建了一个变量recectionInprogress并将其设置为false。

  2. 然后将'Update'内部的函数转换为独立函数UpdateComponentOrderDB()

  3. 内部'update'

        if (receiveInProgress == true) {
            console.log("Receive in progress! Update will happen on its own.")
        } else {
            updateComponentOrderInDB();
        }
    
  4. 现在,在"接收"的开头,我将ReceionInprogress设置为True,在Ajax调用结束时,我将其设置回FALSE并运行UpdateTaTeComponentOdderIndb()。现在所有人都按照所需的顺序工作!

'接收'和'更新'回调由可排序的小部件同步调用。不可能"等待" receive函数中的异步调用在'Update'fires之前完成。

您应该以不同的方式处理。您可能根本不需要"更新"功能。AJAX调用完成后,您可以在createNewComponentInDB函数中触发您的"排序"。我假设您在AJAX调用的回调中执行$(newItem).attr('id', response);,只需在此行之后立即将分类逻辑放置。

最新更新