Pyk*_*ler 2 javascript infinite-loop goinstant goinstant-platform
我有一个文本区域,我正在与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;
});
})
Run Code Online (Sandbox Code Playgroud)
这会创建一个无限循环,当更新一个文本字段时,即当更改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;
};
}
Run Code Online (Sandbox Code Playgroud)
这样,即使使用js的异步特性,我也可以根据需要生成bounceProtection对象以保护多个密钥.
var myKeyBP = new BounceProtection();
Run Code Online (Sandbox Code Playgroud)
小智 5
一种防止无限传播循环的快速方法:
// 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;
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
588 次 |
| 最近记录: |