简体   繁体   English

如何在作为对象属性的JavaScript函数生成器上进行操作

[英]How to operate on javascript function generator which is an object property

I would like to place js generator as an object property and operate on it from within other object properties. 我想将js生成器放置为对象属性,并在其他对象属性中对其进行操作。 The code execution would be triggered via events. 代码执行将通过事件触发。 Below is short version of the code idea: 以下是代码提示的简短版本:

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

The problem is that the second call starts generator from the beggining (not continue it). 问题是第二个调用从开始开始生成器(不继续)。 I suppose that the problem might be in obj.property1.gener , which returns the generator, but I don't know how to make it works. 我想问题可能出在obj.property1.gener中 ,它返回了生成器,但是我不知道如何使它工作。 I would be grateful for your help!. 感谢您的帮助!

Yes, gener does create a new generator every time it is called. 是的, 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();
  }
};

With this you can do 有了这个你可以做

obj.generate();
obj.addMonthsGrid();
obj.generator.next();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM