我可以使用函数生成器作为事件处理程序吗?

Can I use function generator as event handler?

我有一个 HTMLCollection 列表:

<div class="demo">Access me by class[1]</div>
<div class="demo">Access me by class[2]</div>
<div class="demo">Access me by class[3]</div>
<div class="demo">Access me by class[4]</div>

我有一个JS脚本:

var getElements = document.getElementsByClassName("demo");
const generatorObject = generatorFunction();

function* generatorFunction(e) { 
    for (i = 0; i < getElements.length; i++) { 
        yield getElements[i];
    }
}

generatorObject.next(); // each time pressed a key down will invoke this line 
// after invoking 6th time it will give {value: undefined, done: done}

我的目标是编写一个基于 .addEventListener("keydown", generatorFunction) 方法的 keyboardEvent,事件处理程序将作为函数生成器呈现,即上面提到的 generatorFunction。这是好事还是坏事?

直接使用生成器函数作为事件回调没有任何意义,因为调用函数不会执行它的主体,它会生成和return (无处)迭代器。

相反,您需要将它包装在另一个与迭代器对话的函数中。我不确定您的具体用例是什么(您谈论的是按键事件,但没有说是什么元素)。但这是一个通用设置——在这个例子中,我在每次按键时从数组中生成一个数字。在最后一个数字上,done 设置为 true。

function* generator() {
    let toYield = [1, 2, 3, 4];
    for (let i=0; i<toYield.length-1; i++) yield toYield[i];
    return toYield.pop(); //return final item in array, which sets iterator to done
}
const iterator = generator();
document.querySelector('input').addEventListener('keydown', evt => {
    let yielded = iterator.next();
    console.log(yielded);
});

Fiddle

参考了一些代码,非常感谢@Mitya

var toYield;
function* generator() {
    toYield = []; // five iterable yieldedObject(s) will be pushed
    var getElements = document.getElementsByClassName("demo");
    for (let i=0; i<getElements.length; i++) 
    yield toYield.push(getElements[i]); 
}

const iterator = generator();
var yieldedObject;
window.addEventListener('keydown', ()=> {
   yieldedObject = iterator.next();
   console.log(yieldedObject); // yieldedObject has value:xyz/undefined and flag: false/done
   colorizeIt();
});

function colorizeIt() {
for (const items of toYield){
 switch(true) {
  case yieldedObject.value >= 0:
    items.style.backgroundColor = "yellow";
    break;
  default:  items.style.backgroundColor = "white";
}
    
    
}
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Accessing Elements in the DOM</title>

  <style>
    html { font-family: sans-serif; color: #333; }
    body { max-width: 500px; margin: 0 auto; padding: 0 15px; }
    div { padding: 10px; margin: 5px; border: 1px solid #5e41ff; }
  </style>

</head>

<body>

  <h1>Simple keyboard event via event generator</h1>

    <div class="demo">Access me by class[0]</div>
    <div class="demo">Access me by class[1]</div>
    <div class="demo">Access me by class[2]</div>
    <div class="demo">Access me by class[3]</div>
    <div class="demo">Access me by class[4]</div>

</body>
</html>

一切正常!非常感谢!