【发布时间】:2019-08-12 08:46:24
【问题描述】:
我使用 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 的对话,我能够通过使用“标志概念”来解决这个问题。
我创建了一个变量 receiveInProgress 并将其设置为 false。
然后把'update'里面的函数变成一个独立的函数updateComponentOrderInDB()
-
在“更新”内部
if (receiveInProgress == true) { console.log("Receive in progress! Update will happen on its own.") } else { updateComponentOrderInDB(); } 现在,在“接收”开始时,我将 receiveInProgress 设置为 true,在 Ajax 调用结束时,我将其设置回 false 并运行 updateComponentOrderInDB()。现在一切都按所需的顺序工作了!
【问题讨论】:
-
您可以为此发布一个示例 html 吗?此外,
async-await与回调实际上是一回事,因此在这种情况下无关紧要。 -
@Jane 你的意思是带有元素的可排序列表吗?进行了编辑。
标签: jquery node.js ajax async-await jquery-ui-sortable