這是另一種不使用間隔的方法。每次按下某個鍵時,都會啓動1s超時,然後執行更新。如果一個按鍵被按下的次數超過1秒,那麼速度太快,只需重置定時器即可。您也可以對其他事件使用相同的計時器和相同的更新功能,使其具有可擴展性。
function update() {
$scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
console.log("Updating the model - key - " + attr['name']);
});
}
var timeout = 1000, timer;
ck.on('key', function() {
clearTimeout(timer);
timer = setTimeout(function() {
update();
}, timeout);
});
或者,如果您想每按n次鍵更新一次,您可以按照以下方式進行操作。
var timeout = 1000, timer, updating = false;
function update() {
$scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
console.log("Updating the model - key - " + attr['name']);
updating = false;
});
}
ck.on('key', function() {
if (updating === true) return;
updating = true;
timer = setTimeout(function() {
update();
}, timeout);
});
然而,如果你需要檢查的內容發生了變化,而不是某個鍵被按下時,你可以使用ck.checkDirty()
和ck.resetDirty()
做間隔檢查相結合。還有一個change
事件,但我沒有測試過它。有許多不會觸發事件的內容更改,例如加粗一些文本,通過圖標添加圖像或HR,更改表格屬性以及拖動圖像等。
CKEditor已經實現了這樣的功能。請參閱:[CKEDITOR.tools.eventsBuffer](http://docs.ckeditor.com/#!/api/CKEDITOR.tools-method-eventsBuffer)。 – oleq