用函数回调封装JavaScript



我有一个chrome扩展,里面有很多行代码。越来越多的人要求我在其他浏览器(如firefox)上也提供该扩展。

因为它是chrome的扩展,所以包含了许多chrome特定的功能。在我开始的时候,我想把所有chrome特定的方法放在一个javascript文件"chrome.js"中,并用我自己的方法封装chrome函数,这样我就可以轻松地创建其他浏览器特定的方法。

这对于简单的方法来说很容易:

function geti18nMessage(messageId) {
   return chrome.i18n.getMessage(messageId)
}

但是如何封装返回函数的(异步)方法

示例:

chrome.runtime.sendMessage(
            {
                Action: "Load"
            }, function (response)
    {
    console.log("response is "+response);
    });

这并不是真正针对chrome的,但chrome问题是我问题的一个真实例子。

您可以像传递其他参数一样传递函数:

function sendMessage(options, fn) {
   return chrome.runtime.sendMessage(options, fn);
}

这假设您在所有平台上都致力于相同的Chrome回调场景。如果你想自定义回调,使其成为你自己设计的东西,那么你可以这样替换它:

function sendMessage(options, fn) {
   return chrome.runtime.sendMessage(options, function() {
       // do any processing of the chrome-specific arguments here
       // then call the standard callback with the standard arguments you want to
       // support on all platforms
       fn(...);
   });
}

最新更新