Call function in app.js from inside window
Hey I kinda had a similar question earlier and it was answered, but for some reason it wont let me call a regular function.
I have app.js with a window linked to login.js
I want to call a function in app.js from login.js
In login.js:
var win = Titanium.UI.currentWindow;
win.enter();
In app.js:
function enter()
{
alert("enter called");
}
When I go to call the enter function I get this error:
[WARN] Exception in event callback. {
expressionBeginOffset = 1435;
expressionCaretOffset = 1444;
expressionEndOffset = 1446;
line = 71;
message = "Result of expression 'win.enter' [undefined] is not a function.";
name = TypeError;
sourceId = 238891200;
sourceURL = "login.js";
}
4 Answers
-
Your window is a different context than the main app.js, to call the method you can try firing & listening for events. This blog entry explains a lot about execution contexts as well as examples of events. If you need to pass parameters to the method you can also do that through the event.
App.js
Ti.App.addEventListener('myCustomEvent', function(event) { enter(); });
login.js
Ti.App.fireEvent('myCustomEvent', {});
-
Try this in your app.js:
var enter = function() { alert("enter called"); } var w = Ti.UI.createWindow({url:'login.js'}); w.enter = enter; w.open();
-
Advice:
If you want to use the same code on android, use the customEvent approach.
On Android all function references are converted to Strings/Objects not references. That makes callbacks completely unusable.This is important and should at least be mentioned in the Titanium.UI.window.
-
Thank you both. Both methods worked. I am going to use the custom events though. I am more familiar with that from AS3 anyway.