【发布时间】:2016-06-05 04:39:56
【问题描述】:
我有一个监听器来监听内容的变化,一旦内容被修改,它就会发出处理函数:
$('#editor').on('onchange', () => changeHandler('...','...'));
function changeHandler(filePath, content){
var ws = fs.createWriteStream(filePath, 'utf8');
ws.write(content);
}
我的问题是'onchange'发生的太频繁了,所以'write file'处理的太频繁了,期间可能会丢失数据。 有人可以给点建议吗?
更新 现在我根据以下答案更改了代码:
this.buffer = null; //used to cache
// once content changed, maybe too often
changeHandler() {
if (this.editor.curOp && this.editor.curOp.command.name) {
var id = $('.nav-items li.active .lk-hosts').attr('data-hosts-id');
var content = this.editor.getValue();
// cache data, not immediately write to file
this.buffer = {id: id, content: content};
}
}
setInterval(()=> {
// means there's data in cache
if (this.buffer !== null) {
let id = this.buffer.id;
let content = this.buffer.content;
// reset cache to null
this.buffer = null;
// write file
this.writeContent(id, content, (err)=> {
})
}
}, 800);
感谢所有答案!
【问题讨论】:
-
您可以限制事件,使其最多每 X 秒发生一次。
-
为什么不让'onchange'控制一个计时器,当它倒计时到0时,保存内容。快速打字只会将计时器重置为满,并且您只会在打字停止时间足够长以使计时器达到 0 时保存。
-
只是好奇,你如何在同一段代码中拥有内容更改监听器和
fs.createWriteStream()?还是其中一个在浏览器中,另一个在服务器中? -
@jfriend00 可能是这样,但我有这个的浏览器仿真,请检查我的答案并分享想法
-
@MedetTleukabiluly - 我对你的猜测不感兴趣 - 我希望 OP 告诉我们真正的环境和真正的问题是什么,以便我们提供最佳答案。到目前为止,OP 没有对问题做出回应。
标签: javascript node.js asynchronous