1

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!

2
  • 1
    What do you mean when say you can't run your app? Do you get any specific errors? What exactly does myFile.js do? You may not access the DOM but you may be relying on window or some other globals that aren't present. Commented Jul 17, 2015 at 18:37
  • Does your myFile.js properly export its variables? Commented Jul 17, 2015 at 18:38

1 Answer 1

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)...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.