2017-04-21 34 views
0

我試圖取代一個電話與一個迭代函數,然後產量提醒()參考把自己從一個JavaScript生成器對象

見下面一個非常基本的片斷

var globalFunction; 
 

 
function* test() { 
 

 
    /* 
 
    test is a generator function. It will return an iterator function 
 
    after this iterator function yields, I want it to continue when the 
 
    button2 is clicked. (Just as if the button2 is the button in an alert) 
 
    Note than here the iterator function still doesn't exist, it will be 
 
    returned at the end of the generator function 
 
    */ 
 
\t var ele = document.getElementById("btn2"); 
 
\t ele.onclick = function() { 
 
\t \t globalFunction.next(); 
 
\t \t /* use some kind of 'this' here ? */ 
 
\t }; 
 
\t yield 1; 
 

 
\t console.log ("test2"); 
 
\t yield 2; 
 
} 
 

 

 
function btn1() { 
 
\t console.log ("btn1"); 
 

 
\t var mytest = test(); 
 
\t globalFunction = mytest; 
 
\t 
 
\t var res = mytest.next(); 
 
\t console.log (res.value); 
 
}
<button id="btn1" onclick="btn1()">BTN1</button> 
 
<button id="btn2">BTN2</button>

這段代碼正在工作,因爲我將迭代器存儲在全局變量中,然後在需要時將它賦值給onclick。

但我不喜歡這種工作方式。

我想能夠以某種方式訪問​​迭代器函數。在那裏有關於使用這個的評論。

知道這個不會在這裏工作!

但是,在這裏沒有任何方法可以獲得對迭代器函數的引用嗎?

又如澄清:

var globalFunction; 
 
var span = document.getElementById("res"); 
 

 
function* test() { 
 

 
    /* 
 
    test is a generator function. It will return an iterator function 
 
    after this iterator function yields, I want it to continue when the 
 
    button2 is clicked. (Just as if the button2 is the button in an alert) 
 
    Note than here the iterator function still doesn't exist, it will be 
 
    returned at the end of the generator function 
 
    */ 
 
    var ele = document.getElementById("btn2"); 
 
    ele.onclick = function() { 
 
    globalFunction.next(); 
 
    /* use some kind of 'this' here ? */ 
 
    }; 
 

 
    var x; 
 
    for (x = 1;; x++) { 
 
    if (x % 7 == 0) { 
 
     span.innerHTML = x + ' is divisible by 7. Hit btn2 to continue'; 
 
     yield; 
 
    } 
 
    } 
 
} 
 

 

 
function btn1() { 
 
    console.log("btn1"); 
 

 
    var mytest = test(); 
 
    globalFunction = mytest; 
 

 
    var res = mytest.next(); 
 
}
<button id="btn1" onclick="btn1()">BTN1</button> 
 
<button id="btn2">BTN2</button> 
 
<span id="res">Hit BTN1</span>

+0

@brk函數*將函數定義爲生成器。然後,迭代器函數中的yield可用。 – vals

+0

全局變量很難避免,因爲2個不同的onclick處理程序需要訪問相同的迭代器實例。您可以考慮將整個代碼示例(包括變量)包裝在「容器」函數中,以限制範圍。 –

+1

在更高層次上;你究竟想在這裏完成什麼? – charlietfl

回答

0

最後,我想出了一個解決方案爲具有發電機對象內部本身的引用(排序的)

function runGenerator (gen) { 

    function* wrapper() { 
     var reflection = yield; 

     yield* gen(reflection); 
    } 
    var genObj = wrapper(); 
    genObj.next(); 
    return genObj.next(genObj); 
}