【问题标题】:Phonegap plugin - module.exportsPhonegap 插件 - module.exports
【发布时间】:2015-07-14 11:51:57
【问题描述】:

插件的 javascript 和视图的 javascript 之间如何传递对象?我正在玩“apache cordova 3 programming”书中的示例代码,但我被卡住了......

在我的 plugin.xml 中,我将命名空间设置为“mool”

<js-module src="plugin.js" name="moool">
    <clobbers target="mool" />
</js-module>

插件.js

var mol = {
    calculateMOL : function() {
        return 42; 
    }
};

var molll = {
    calculateMOLLL : function() {
        return 42222; 
    }
};

module.exports = molll;
module.exports = mol;

index.html

<!DOCTYPE html> <html>
<head>
<title>Meaning of Life Demo</title>
<meta http-equiv="Content-type" content="text/html;
charset=utf-8">
<meta name="viewport" content="user-scalable=no,
initial-scale=1, maximum-scale=1, minimum-scale=1,
width=device-width;" />
<script type="text/javascript" charset="utf-8"
src="cordova.js"></script>

    <script type="text/javascript" charset="utf-8">

    function onBodyLoad() { 
        document.addEventListener("deviceready", onDeviceReady,
        false);
    };

    function onDeviceReady() { 
        //alert("onDeviceReady");
    };


    function doMOL() {
        var res = mool.calculateMOL(); 
        alert('Meaning of Life = ' + res);
    };

    function doMOLL() {
        var res = mool.calculateMOLLL(); 
        alert('Meaning of Life = ' + res);
    };

    </script>

</head>


<body onload="onBodyLoad()"> 
<h1>MoL Demo</h1>
<p>This is a Cordova application that uses my custom
Meaning of Life plugin. </p>

<button onclick="doMOL();">Button1</button>
<button onclick="doMOLL();">Button2</button>

</body>
</html>

但是当我运行它时,只有第二个按钮可以工作......有人可以给我一个解释吗?

我已经尝试过同时导出两个对象,例如:

module.exports = molll, mol;

但是还是不行……

【问题讨论】:

  • 我知道我可以将这两种方法放在一个对象中,然后再调用它——但是如果你只能处理一个对象,那么 module.exports 有什么意义呢?

标签: javascript cordova plugins phonegap-plugins


【解决方案1】:

这是一个迟到的评论,但可能会让其他人受益。对我有用的是类似于以下内容:

  1. 尝试重写plugin.js函数如下:

    module.exports.calculateMOL = function() { return 42; };

    module.exports.calculateMOLLL = function() { return 42222; };

  2. 删除最后的两个导出语句(即module.export = mol;= molll;

这应该允许访问上述index.html 文件中所示的两种方法。

【讨论】:

    【解决方案2】:

    似乎每个定义它只分配一个对象!

    “clobbers 元素指定分配给加载的 JavaScript 对象的 JavaScript 对象。”

    【讨论】:

      【解决方案3】:

      我注意到在我构建的应用程序中,module.exports 属性采用了一个数组,如下所示。这将允许您将两个项目都放在那里(?)(我只是在这个 sn-p 中显示数组的一个对象。)

      cordova.define('cordova/plugin_list', function(require, exports, module) {
      module.exports = [
          {
              "file": "plugins/org.apache.cordova.dialogs/www/notification.js",
              "id": "org.apache.cordova.dialogs.notification",
              "merges": [
                  "navigator.notification"
              ]
          }, etc
      

      【讨论】:

        猜你喜欢
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-15
        • 2017-10-01
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多