0
votes

I am trying to load protobuf js file using require but I am getting following exception on console.

02-21 11:18:06.445 9130-9130/com.p.protoextensiontest I/chromium: [INFO:CONSOLE(5)] "Uncaught Error: Module name "js/proto/data_main_1_pb" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded", source: file:///android_asset/www/js/require.js (5)
"Uncaught Error: Mismatched anonymous define() module: function p(){   

Here is my code of index.js

var proto = require('js/proto/aaa_bbb_1_pb');

function onCreate(){
    console.log("in onCreate");
    parseProto();
}
function parseProto(){
    var name = proto.person.personName;
}

Here is my index.html

<head>
    <title> Testing proto extension</title>
    <script src="js/require.js"></script>
    <script src="js/google-protobuf.js"></script>
    <script src="js/index.js"></script>

</head>
<body>
    <button type="button"  onclick="onCreate()"> Create Data</button> <br/> 
</body>

I am newbie on javascript and node.js. Please provide any reference.

1

1 Answers

2
votes

The module you show in index.js is in the CommonJS format. It does not have a wrapper and makes require calls that contain a single string argument.

However, you are using RequireJS to load it. RequireJS is an AMD module loader, not a CommonJS module loader. You don't have to completely rewrite your require calls to use the AMD format (a require call with an array of dependencies and a callback) but you have to at least wrap your module's code in a define call, like this:

define(function (require) {
  var proto = require('js/proto/aaa_bbb_1_pb');

  function onCreate(){
      console.log("in onCreate");
      parseProto();
  }

  function parseProto(){
      var name = proto.person.personName;
  }
}

Note that onclick=onCreate() still won't work. One of the goals of using modules is to avoid putting everything in the global space. So onCreate is not accessible to onclick. The minimal way to make it accessible would be to add window.onCreate = onCreate after your definition of the function but I do not recommend this. You should either add an exported function that you can call at initialization with the button object and that will call addEventListener("click", onCreate), or the module could search for a specific element on the page (by ID, class name, whatever) and call addEventListener("click", onCreate).