私はそれをダブルクリックすると、それを編集をユーザーに許可するコンテンツのセクションを持っています。ユーザーがコンテンツを変更してから2秒間停止すると、更新されたコンテンツがサーバーに送信されて保存されます。置き換えタイムアウトイベントが発生2回以上(時には)
これを行うには、2秒カウントダウンを開始するセクションにinput
イベントリスナーをバインドしました。カウントダウンが既に存在する場合は、前者がキャンセルされ、代わりに新しいイベントが開始されます。カウントダウンの最後に、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();
});
}
あなたが参照するには、 '場合(toSaveTimeout){' 'ブロックにconsole.log'を追加しようとしましたもしそれが入っていたら? – IMTheNachoMan
'makeEditable'関数を呼び出すたびに、toSaveTimeoutはこの関数スコープにバインドされているため、未定義です。あなたのテスト 'if(toSaveTimeout)'は常に失敗します。 – Franck
あなたは 'makeEditable'を2回呼び出さないようにしてください。 –