如何在javascript中阻止输入

时间:2017-02-20 19:29:43

标签: javascript blocking

从概念上讲,我在javascript中需要做的是:

// A) set up stuff

// B) collect values from input
do {
    var key = readKey();
    // do stuff like loading arrays, objects, etc based on this sequential input
} while (key != '.') // period signifies completion

// C) continue to do other stuff that can only be done once the arrays and objects from before are completely loaded.

我知道IO在javascript中是非阻塞的。所以我尝试在setTimeout构造中设置键盘侦听器和循环,但是我无法避免程序执行飞到C)和错误输出,因为作为B)一部分的所有先决条件处理都没有完成。

以下是我的尝试:

// A) prepare stuff
var digrams = type() // B
// C) deal with digrams (errors out if digrams not complete)

function type() {
  var loopid;

  var loop = function() {
    // NOP
  };

  document.onkeypress = function (e) {
    e = e || window.event;
    var char = String.fromCharCode(e.keyCode);
    ...
    if (char=='.') {
     document.onkeypress = null;
     clearInterval(loopid);
     return digrams; // arr of obj composed thru key input
    }
  } // keylistener

  // Start the type loop
  loopid = setInterval( loop, 10);
}   

我真的需要一种在这里“反对”javascript的方法。任何示例代码都将受到赞赏。

2 个答案:

答案 0 :(得分:1)

您可以使用Promise将值异步返回.then()

// A) prepare stuff
var digrams = type();
digrams
.then(funcion handleSuccess(value) {
  // do stuff with `value` : `arr` passed to `resolve()`
}
, function handleError(err) {
  // handle error
}); // B
// C) deal with digrams (errors out if digrams not complete)

function type() {
  return new Promise(function(resolve, reject) {
    var loopid;

    var loop = function() {
      // NOP
    };

    document.onkeypress = function (e) {
      e = e || window.event;
      var char = String.fromCharCode(e.keyCode);
      ...
      if (char=='.') {
        document.onkeypress = null;
        clearInterval(loopid);
        resolve(arr);
        // return digrams; // arr of obj composed thru key input
      }
      // reject(new Error("error message"));
    } // keylistener

    // Start the type loop
    loopid = setInterval( loop, 10);
  });
}   

答案 1 :(得分:0)

你可以把“阻止”'将代码编入函数,然后在密钥匹配.

时运行该函数

类似的东西:

function myContinue(){
   ...your blocked code
}

document.onkeypress = function (e) {
... assuming your keypress code is working
    if (char=='.') {
       myContinue();
    }
}

如果要访问continue函数之外的变量,请在函数外声明它们:

var arrayToLoad;

function myContinue(){
  console.log(arrayToLoad);
}

document.onkeypress = function(e) {
   ...
   arrayToLoad.push(char);
   ...
      myContinue();
   ...
}

或者,您可以将vars传递给函数

function myContinue(diagrams){
...
}

document.onkeypress = function(e) {
...
  myContinue(diagrams);