我有一段内容允许用户在双击它时进行编辑。如果用户更改内容然后停止2秒,则更新的内容将被发送到服务器以进行保存。替换的超时事件触发两次或更多(有时)
为此,我已将一个input
事件侦听器绑定到开始2秒倒计时的那部分,并且如果已经有倒计时,则前者将被取消,而另一个将开始。在倒计时结束时,使用新数据将HTTP POST请求发送到服务器。
问题是,有时在倒计时结束时,我看到有2个或更多的请求被发送,就好像在插入新的插入前倒计数没有被取消一样,我不知道为什么。
有问题的代码如下:
//this function is bound to a double-click event on an element
function makeEditable(elem, attr) {
//holder for the timeout promise
var toSaveTimeout = undefined;
elem.attr("contentEditable", "true");
elem.on("input", function() {
//if a countdown is already in place, cancel it
if(toSaveTimeout) {
//I am worried that sometimes this line is skipped from some reason
$timeout.cancel(toSaveTimeout);
}
toSaveTimeout = $timeout(function() {
//The following console line will sometimes appear twice in a row, only miliseconds apart
console.log("Sending a save. Time: " + Date.now());
$http({
url: "/",
method: "POST",
data: {
action: "edit_content",
section: attr.afeContentBox,
content: elem.html()
}
}).then(function (res) {
$rootScope.data = "Saved";
}, function (res) {
$rootScope.data = "Error while saving";
});
}, 2000);
});
//The following functions will stop the above behaviour if the user clicks anywhere else on the page
angular.element(document).on("click", function() {
unmakeEditable(elem);
angular.element(document).off("click");
elem.off("click");
});
elem.on("click", function (e) {
e.stopPropagation();
});
}
您是否尝试过一个'console.log'添加到'如果(toSaveTimeout){'块看如果它进入了它? – IMTheNachoMan
每次调用'makeEditable'函数时,toSaveTimeout都是未定义的,因为它被绑定到这个函数范围。你的测试'if(toSaveTimeout)'总是会失败。 – Franck
确保你不要调用'makeEditable'两次 –