[英]Why my global variable isn't seen by another function?
This is the most irritating problem I have ever faced: 这是我遇到的最烦人的问题:
var appslst = [];
function f1()
{
chrome.management.getAll(function(lst)
{
appslst = lst;
});
}
function f2() // this function isn't working!!
{
var l = appslst.length;
var ind = 0;
while(ind < l)
{
document.getElementById("here").value = document.getElementById("here").value.concat(String(ind), ". ", appslst[ind].name, "\n");
ind += 1;
}
}
function f3()
{
f1();
f2();
}
I believe that appslst
- as it's a global variable - should be seen in both functions f1()
and f2()
, but the above code isn't working and I have no idea why. 我相信
appslst
- 因为它是一个全局变量 - 应该在函数f1()
和f2()
看到,但上面的代码不起作用,我不知道为什么。
Also, I have tried the following code (and it's working) : 另外,我尝试了以下代码(并且它正在工作):
var appslst = [];
function f1()
{
chrome.management.getAll(function(lst)
{
appslst = lst;
var l = appslst.length;
var ind = 0;
while(ind < l)
{
document.getElementById("here").value = document.getElementById("here").value.concat(String(ind), ". ", appslst[ind].name, "\n");
ind += 1;
}
});
}
Some more details. 更多细节。 I'm learning how to build extension for Google Chrome.
我正在学习如何为Google Chrome构建扩展程序。 I have download the sample: http://code.google.com/chrome/extensions/examples/extensions/app_launcher.zip from this link: http://code.google.com/chrome/extensions/samples.html .
我已从此链接下载示例: http : //code.google.com/chrome/extensions/examples/extensions/app_launcher.zip : http : //code.google.com/chrome/extensions/samples.html 。 I had a look over the code and found the same code I wrote, except that it's working!
我查看了代码并找到了我编写的相同代码,但它正在工作!
Here's the part I'm talking about: 这是我正在谈论的部分:
function onLoad()
{
chrome.management.getAll(function(info)
{
var appCount = 0;
for (var i = 0; i < info.length; i++) {
if (info[i].isApp) {
appCount++;
}
}
if (appCount == 0) {
$("search").style.display = "none";
$("appstore_link").style.display = "";
return;
}
completeList = info.sort(compareByName);
onSearchInput();
});
}
chrome.management.getAll
is asynchronous - hence you need to pass a function that is executed only when Chrome is done executing getAll
. chrome.management.getAll
是异步的 - 因此你需要传递一个只在Chrome完成执行getAll
时执行的函数。
This means that f1(); f2();
这意味着
f1(); f2();
f1(); f2();
will go like this: 会是这样的:
f1
is called f1
被调用 getAll
is called (that's what f1
is doing) getAll
(这就是f1
正在做的事情) f2
is called f2
appslst
(that's what f2
is doing) appslst
(这就是f2
正在做的事情) getAll
is done; getAll
完成了; the function passed to it is called appslst
is filled with data from getAll
(that's what the passed function is doing) appslst
充满了来自getAll
数据(这是传递的函数正在做的事情) In other words, appslst
is still empty at the time f2
is called. 换句话说,在调用
f2
, appslst
仍然是空的。 So you need to suspend f2()
as well: 所以你需要暂停
f2()
:
chrome.management.getAll(function(lst){
appslst = lst;
f2(); // only run when getAll is done and appslst is filled
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.