Hi I want to access a function from other .js file.Actually there are two .js files.In one js file i have write the function as.This is db.js
function quizfun() { var quizes = db.execute('select * from Quiz'); while (quiz.isValidRow()) { var counter = 0; dataArray[counter] = quiz.fieldByName('Quiz_Text'); quiz.next(); alert(dataArray[counter]); counter++; }; return dataArray; }and i am accessing it from other js file which is quizwin.js like this but it is not accessing function
var quiz_db = Titanium.include('db.js'); quiz_db.quizfun();
2 Answers
Accepted Answer
Hi
If you use CommonJS techniques you will be able to achieve what you are after.
If you use the following simple syntax you can use those functions elsewhere;
newfile.js
function internalonly() { // this is not available outisde as it is not in the exports entry below } function somefunc() { } function someotherfunc() { } exports.somefunc = somefunc; //public function exports.someotherfunc = someotherfunc; //public functionYou would then use the require keyword in your code and not the include one;
var Mod = require('/newfile') // do not include the dot js Mod.somefunc(); // you then call it like thisSo your code would look something like this;
db.js
function quizfun() { var quizes = db.execute('select * from Quiz'); while (quiz.isValidRow()) { var counter = 0; dataArray[counter] = quiz.fieldByName('Quiz_Text'); quiz.next(); alert(dataArray[counter]); counter++; }; return dataArray; } exports.quizfun = quizfun;You then call it in other file like;
var quiz_db = require('/db'); quiz_db.quizfun();You can call require('/db'); in as many other parts of your app as you need.
As you not from my first example you add many functions inside a single CommonJS module, so you can group logically similar functions, you can also include private functions that are not exposed externally - good for supporting methods.
Top; keep the CommonJS modules small and specific this really helps you manage your code and your app.
You can do this with a commonjs module.
db.js:
function quizfun() { var quizes = db.execute('select * from Quiz'); while (quiz.isValidRow()) { var counter = 0; dataArray[counter] = quiz.fieldByName('Quiz_Text'); quiz.next(); alert(dataArray[counter]); counter++; }; return dataArray; } module.exports = quizfun;quizwin.js:
var quiz_db = require('db'); quiz_db.quizfun();
Your Answer
Think you can help? Login to answer this question!