Using JavaScript files in NativeScript

筅森魡賤 提交于 2019-12-14 04:20:08

问题


I am learning NativeScript. As part of that, I'm trying out a basic project. In that project, I'm trying to use a JavaScript file that I use for string manipulation. This file does NOT require access to browser elements like the DOM. Yet, I can't run my app when I include the file. At this time, I have the following in my ./app/home/index.js file:

var MyFile = require('../app/code/myFile.js');
...
var prefix = myFile.GetPrefix(someStringValue);

For more background:

  1. I've included the file in ./app/code/myFile.js.
  2. I've referenced the file as shown above

Here is what myFile.js looks like:

function MyClass() {}
module.exports = MyClass;
MyClass.test = function(msg) {
  console.log(msg);
};

How can I use some existing JavaScript in a NativeScript app?

Thank you!


回答1:


You need an instance of MyClass in index.js. You can instantiate MyClass either in:

  1. index.js:

    var myFileModule = require('../app/code/myFile.js');

    var myFile = new myFileModule.MyClass();

OR...

  1. myFile.js:

    module.exports = new MyClass();

:: Note that if you do #2 above, in your code...

var MyFile = require('../app/code/myFile.js');

... the MyFile variable already IS an instance of MyClass.

:: A small, unrelated suggestion on coding style: It's better to name your variable(s) myFile instead of MyFile (note the first lowercase letter in myFile)...



来源:https://stackoverflow.com/questions/31482486/using-javascript-files-in-nativescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!