Reputation: 1264
This is just out of curiosity, as I program games for a living, not web applications.
What is the reason that the Chrome extension API (chrome.*
family) consists almost entirely of callback setters? I'm talking about this programming model that at first sight appears to be abusing closures:
// do something with the Tab object of an activated tab
chrome.tabs.onActivated.addListener(function (activeInfo) {
chrome.tabs.get(activeInfo.tabId, function(theTab) {
foo(theTab);
});
});
I'm used to having getters simply return the requested value and just find this interesting. Is this because all these methods (such as getLastFocused
here) actually only schedule asynchronous tasks for the browser engine?
Upvotes: 2
Views: 193
Reputation: 340
I was wondering something similar and came across a good explanation, maybe someone will find this useful as I did:
[The reason for using callbacks in the APIs] has to do with Google Chrome's multi-process architecture. Web pages and JavaScript run in processes which are not only separate from each other, but also from the main browser process which alone has the ability to do things like read & write to the local file system. This is an important security and stability feature for Google Chrome. If calls like this were synchronous, your extension would have to stop everything and wait for the browser process to respond to the request, all the while the user may be trying to interact with the UI of your extension which has become unresponsive. Using asynchronous APIs is more challenging, but it's in the service of the best user experience.
This is from the transcript of this video on the extension API design.
Upvotes: 4
Reputation: 2674
From my perspective, one of the reasons, why most methods in the chrome.*
APIs are asynchronous, is that extensions usually have to deal with the user interactions. Any asynchronous API in general leads to better application responsiveness. So, developers of the chrome.*
APIs simply provide an easier way to write efficient extensions, that will not slow down Google Chrome, making users disappointed.
Upvotes: 0
Reputation: 897
This is a combination of an event handler and some asynchronous actions. In addition, the way scoping works in javascript can be a bit iffy; using closures creates a reliable scope that allows data to be passed about that just couldn't be done in another manner.
Upvotes: 1