gpt4 book ai didi

javascript - 两个同步事件创建一个无限循环

转载 作者:行者123 更新时间:2023-11-29 16:15:08 26 4
gpt4 key购买 nike

我有一个正在与 GoInstant 同步的文本区域.这是代码的样子:

var myRoom = platform.room('myRoom');
var myKey = myRoom('myKey');

// Listen to set events on the platform key and update a textarea
myKey.on('set', function(textAreaContent) {
$('textarea').val(textAreaContent);
});

// When the textarea changes, set the platform key
$('textarea').on('change', function(){
var textAreaContent = $(this).val();
myKey.set(textAreaContent, function(err) {
if (err) throw err;
});
})

这会创建一个无限循环,当更新一个文本字段时,即当更改 textarea 的值时,这会触发平台键更新,从而无限地更改 textarea 的值......

编辑:根据最佳答案,我想出了以下构造函数:

function BounceProtection() {
var remoteUpdate = false; // remote toggle
this.local = function(cb) {
if (remoteUpdate) return;
cb();
};
this.remote = function(cb) {
remoteUpdate = true;
cb();
remoteUpdate = false;
};
}

这样,我可以根据需要生成 bounceProtection 对象来保护多个 key ,即使 js 的异步特性也是如此。

var myKeyBP = new BounceProtection();

最佳答案

防止无限传播循环的快速方法:

// Infinite loop prevention
var bounceProtection = {
remoteUpdate: false, // remote toggle
local: function(cb) {
if (this.remoteUpdate) return;
cb();
},
remote: function(cb) {
this.remoteUpdate = true;
cb();
this.remoteUpdate = false;
}
};

var myRoom = platform.room('myRoom');
var myKey = myRoom.key('myKey');

myKey.on('set', function(textAreaContent) {
bounceProtection.local(function() {
$('textarea').val(textAreaContent);
});
});

$('textarea').on('change', function(){
var textAreaContent = $(this).val();
bounceProtection.remote(function() {
myKey.set(textAreaContent, function(err) {
if (err) throw err;
});
});
});

关于javascript - 两个同步事件创建一个无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17700710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com