【发布时间】:2013-06-07 22:44:06
【问题描述】:
我在循环中为数组中的一堆 appId 调用 sendMessage。当我的回调被调用时,我需要检查错误,然后将出现错误的 appId 列入“黑名单”。问题是我尝试过的每一种方法都会导致回调中的 appId 在它被调用时发生变化!所以错误的 appId 会被列入黑名单。
我尝试了三个版本(见下文)。一个从不列入黑名单,另外两个做错了:
**这个黑名单错误的一个**
for ( var appName in apps )
{
var app = apps[ appName ];
var appId = app[ "appId" ];
//Send message to that app
chrome.runtime.sendMessage(
app[ "appId" ],
app,
function (response)
{
var lastError = chrome.runtime.lastError;
//Want to blacklist apps here
if ( lastError && lastError.message.indexOf( "not exist" ) !== -1 )
{
//This blacklists the wrong one!
myGlobalObject.addToTimeout( appId );
}
}
);
}
**这个也黑名单错误的一个**
for ( var appName in apps )
{
var app = apps[ appName ];
var appId = app[ "appId" ];
//Send message to that app
chrome.runtime.sendMessage(
app[ "appId" ],
app,
function (response)
{
var lastError = chrome.runtime.lastError;
//Want to blacklist apps here
if ( lastError && lastError.message.indexOf( "not exist" ) !== -1 )
{
//This blacklists the wrong one!
myGlobalObject.addToTimeout( this[ "appId" ] );
}
}.bind( app )
);
}
** 这个永远不会黑名单 **
for ( var appName in apps )
{
var app = apps[ appName ];
//Send message to that app
chrome.runtime.sendMessage(
app[ "appId" ],
app,
function (response)
{
var lastError = chrome.runtime.lastError;
//Want to blacklist apps here
if ( lastError && lastError.message.indexOf( "not exist" ) !== -1 )
{
//Somehow this NEVER blacklists it!
myGlobalObject.addToTimeout( app[ "appId" ] );
}
}
);
}
【问题讨论】:
标签: javascript google-chrome google-chrome-extension google-chrome-devtools google-chrome-app