2016-05-04 34 views
0

我有一段内容允许用户在双击它时进行编辑。如果用户更改内容然后停止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(); 
    }); 
} 
+0

您是否尝试过一个'console.log'添加到'如果(toSaveTimeout){'块看如果它进入了它? – IMTheNachoMan

+1

每次调用'makeEditable'函数时,toSaveTimeout都是未定义的,因为它被绑定到这个函数范围。你的测试'if(toSaveTimeout)'总是会失败。 – Franck

+0

确保你不要调用'makeEditable'两次 –

回答

1

原来(从上面的评论的帮助),该函数makeEditable被称为不止一次。

在函数的开头添加以下代码两行的固定问题:

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

你知道为什么/如何makeEditable被称为两次吗?无论如何要停止/修复它,所以它永远不会被调用两次,而不是检查它是否已被调用?我的意思是,这两个工作,但我觉得停止它的来源是更好的。 – IMTheNachoMan

+0

(您可能还想将您的答案标记为答案。) – IMTheNachoMan

+1

发生这种情况的原因有很多,它可能是硬件问题,例如疯狂的鼠标发送多次鼠标点击。但其中一个原因也是用户再次双击正确的原因(也许他/她不理解这个概念,或者认为这是保存的方式),并且在这种情况下防止出现问题的唯一方法是上面的代码行。 (是的,我会的,但规则在接受你自己的答案前24小时) –