从内部回调中访问对象文字属性(异步方法)

Ida*_*zit 8 javascript google-chrome-extension

我正在编写一个chrome扩展,需要与书签子树进行交互.这个子树有很多交互,所以我把这个逻辑抽象成一个对象文字,就像这样:

var contextStore = {
    'root_id': undefined,
    'setup': function() {...},      // populates root_id
    'add': function(name) {...},    // uses root_id
    'remove': function(name) {...}, // uses root_id
    // ... etc ...
};

contextStore.setup(); // only once.
contextStore.add("foo");
contextStore.add("bar");
// ... etc
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

我遇到的麻烦是由异步Chrome API(以及我缺少JS-fu)引起的.以机智:

var contextStore = {
    'root_id': undefined,
    'setup': function() {
        chrome.bookmarks.getTree(function(tree) {
           // do some work to find a given folder in bookmarks.
           // now I want to save that folder's id for access in other methods.

           // Fail: 'this' refers to chrome.bookmarks.getTree. 
           this.root_id = computed_thing; // doesn't work!
        });
    }
    // ... etc ...
};
Run Code Online (Sandbox Code Playgroud)

我的问题是:

如何从各种Chrome API方法回调中访问封闭对象文字的成员?

我查看了使用模块模式,但它似乎没有改变的东西,并不是这个代码将被扩展之外的任何东西消耗.

Mat*_*att 9

您需要存储this指向contextStore对象的引用;

var contextStore = {
    'root_id': undefined,
    'setup': function() {
        var that = this; // Store reference here.

        chrome.bookmarks.getTree(function(tree) { 
           that.root_id = computed_thing; // does work!
        });
    }
    // ... etc ...
};
Run Code Online (Sandbox Code Playgroud)

这相当于做;

var contextStore = {
    'root_id': undefined,
    'setup': function() {
        chrome.bookmarks.getTree(function(tree) { 
           contextStore.root_id = computed_thing; // does work!
        });
    }
    // ... etc ...
};
Run Code Online (Sandbox Code Playgroud)

但是,您可以获得不在contextStore任何地方重复使用的好处.