我有一部分内容,允许用户在双击它时对其进行编辑。如果用户更改了内容然后停了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();
    });
}

最佳答案

事实证明(在上述注释器的帮助下)函数makeEditable被多次调用。

在该函数的开头添加以下两行代码可解决此问题:

//if element is already editable - ignore
if(elem.attr("contentEditable") === "true")
    return;

09-25 21:30