2

Chrome 的扩展 API 广泛使用回调函数,因此我经常发现我遇到了范围界定问题。

例子

我正在创建一个选项页面,当我发现chrome.storage.sync.set/get它似乎是完美的解决方案时。

在 options.js 中:

var myOptions = {
    "option1": true,
    "option2": false,
    "option3": false
}

chrome.storage.sync.set(myOptions, function(){});

这就像一个魅力。所以现在在我的内容脚本中,我想访问和使用这些值:

// The documentation says you can pass null to retrieve all stored data
var myOptions = chrome.storage.sync.get(null, function(){});

aFunctionThatNeedsToKnowTheseOptions(myOptions);

哦哦!

不幸的是,你不能这样做。chrome.storage.sync.get()不返回任何东西。所以我需要这样做:

chrome.storage.sync.get(null, function(myOptions){

    var options = myOptions; // Hurray! I have my options

    /* Now all the logic for my function has to be put
       inside this callback. This function might need
       to call other functions outside of this scope.
       This is a mess.
    */
});

问题

如何使我的选项脱离chrome.storage内容脚本中所有其他功能的范围?

4

2 回答 2

4

Your problem is not one of scope, but of timing.

var options; // everyone has access to options.

chrome.storage.sync.get(null, function(myOptions){
    options = myOptions; // Hurray! I have my options
});

console.log(options);                               // No options yet
setTimeout(function(){console.log(options)}, 2000); // Options

I think the best way to deal with the pitfalls of asynchronous programming (specifically the nested callbacks you need to do) is the Promise pattern.

Here is a blog post to get you started with understanding Promises and how they help you structure your code better:

http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

If you find it hard to understand from that particular post, google others until you find one that you do. Keep in mind that promises are not specific to JS, so you might find ideas and explanations for other languages that can help you understand.

于 2013-10-09T16:05:35.860 回答
0

您可以访问当前范围之外的变量。

var myOptions = {
    option1: true,
    option2: false,
    option3: false
};

function aFunctionThatNeedsToKnowTheseOptions () {

    console.log(myOptions);
}

chrome.storage.sync.get(null, function (options) {

    myOptions = options;

    aFunctionThatNeedsToKnowTheseOptions();
});
于 2013-10-09T16:14:15.333 回答