javascript - Two synced events creating an infinite loop -


i have text area synchronizing goinstant. here code looks like:

var myroom = platform.room('myroom'); var mykey = myroom('mykey');  // listen set events on platform key , update textarea mykey.on('set', function(textareacontent) {   $('textarea').val(textareacontent); });  // when textarea changes, set platform key $('textarea').on('change', function(){   var textareacontent = $(this).val();   mykey.set(textareacontent, function(err) {     if (err) throw err;   }); }) 

this creates infinite loop, when updating 1 text field i.e. when changing value of textarea, triggers platform key update, in turn changes value of textarea infinitely ...

edit: based on top answer came following constructor:

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

this way, can generate bounceprotection objects needed protect multiple keys asynchronous nature of js.

var mykeybp = new bounceprotection(); 

a quick method of preventing infinite propagation loop:

// 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;     });   }); }); 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -