我想将js生成器作为对象属性放置,并在其他对象属性中对其进行操作。代码执行将通过事件触发。以下是代码构思的简短版本:
var obj = {
property1: {
generator: function* (){
console.log("gen start");
yield;
console.log("gen part 1");
},
gener: function() {
return obj.property1.generator();
},
addMonthsGrid: function() {
console.log("genNext 1");
obj.property1.gener().next();
}
},
property2: {
exec2: function() {
console.log("intermediate stuff...");
console.log("genNext 2");
obj.property1.gener().next();
}
}
};
/* first event that should run first part of generator: */
obj.property1.addMonthsGrid();
/* second event hat should run second part of generator: */
obj.property2.exec2(); //here it starts from the beggining
问题是第二次调用从开始生成生成器(不继续)。我想问题可能在 obj.property1.gener ,它返回生成器,但我不知道如何使它工作。我很感激你的帮助!
答案 0 :(得分:1)
是的,gener
每次调用时都会创建一个新的生成器。
const obj = {
generatorFunction: function* (){
console.log("gen start");
yield;
console.log("gen part 1");
},
generate: function() {
this.generator = this.generatorFunction();
return this.generator;
},
addMonthsGrid: function() {
console.log("genNext 1");
this.generator.next();
}
};
这样你可以做到
obj.generate();
obj.addMonthsGrid();
obj.generator.next();