2016-08-12 64 views
4

我在尝试使用the chrome.webstore.install(link, success, fail) function内嵌加载谷歌浏览器扩展程序。chrome.webstore.install调用两个回调?为什么?

这是我的网页<head>节中的链接。

<link rel="chrome-webstore-item" 
    href="https://chrome.google.com/webstore/detail/oafp--redacted--ffencd" /> 

这里是按钮。

<input type="button" class="btn btn-default" onclick="getExtension();">Go</input> 

这是Javascript,它出现在关闭</body>标记之前。

<script type="text/javascript"> 

    function getExtension() { 

     function extensionFailed(reason) { 
     console.log("extension Install Failed:", reason); 
     } 

     function extensionInstalled() { 
     console.log("installed"); 
     }; 

     console.log("calling install"); 
     chrome.webstore.install(undefined, extensionInstalled(), extensionFailed()); 
     console.log("install returned"); 

    }; 

    </script> 

单击调用getExtension的按钮可以获得这个顺序的事件,并立即交付给其他人。

  1. “调用安装”(右调用chrome.webstore.install()之前)
  2. “安装”(在成功回调)
  3. “扩展程序安装失败,未定义”(失败回调)
  4. “安装返回。 “ (从电话返回chrome.webstore.install()

在某个地方,异步,我得到内联安装弹出并接受它。

我以为......

  1. 失败回调应该只被调用失败。
  2. 失败的原因应该是有意义的,而不是undefined
  3. 成功回调应推迟到用户接受安装。

我一定在做错事。 ...

回答

4

答:

在这行代码:

chrome.webstore.install(undefined, extensionInstalled(), extensionFailed());

你实际上是通过在extensionInstalled()extensionFailed()()执行的功能。如果你想在将它们作为回调,实际上你可以在函数本身传递你将一个var

chrome.webstore.install(undefined, extensionInstalled, extensionFailed);


函数和变量:

注:这不适用于你的代码,因为你在调用它之前定义了你的函数,这是一个很好的习惯。

您也可以将变量定义为函数,这只会让IMO更容易混淆。举个例子,这两个函数的定义:

var myfunctionVar = function() { 
    console.log('hello, world'); 
} 

function myfunction() { 
    console.log('hello, world'); 
} 

你会以正常的方式(即myfunctionVar()myfunction())调用这些函数。

这两个定义之间的主要区别是myfunctionVar只有在定义本身被执行时才可用,而myfunction立即可用于定义它的父函数的作用域中(或者一旦脚本文件被执行没有父母功能)。这是由于“提升”,这只会让事情变得更加复杂。

在本例中,在分配它之前,您将无法呼叫myfunctionVar()。但是,调用myfunction()并不是这种情况,您可以在父函数的任何位置调用它。

See this answer for a more information.

函数是在Javascript中更复杂(和强大的!)略高于其他语言,所以希望这个答案清除一些东西给你。 You can read about hoisting from W3Schools, here.

+2

正确。即使在调用'.install(...)'方法之前,'()'立即执行两个回调函数。删除这些括号可以确保您将_reference_传递给函数作为参数。 给予更多的信息;当需要调用其中一个回调时,'install'方法在内部将'()'放在回调_references_的后面以执行其中之一作为函数。这是通过'success();'完成的,例如,调用成功回调。 –

+2

*(sma额)*谢谢! –

相关问题