Using Global Function in Titanium - titanium

I am making Titanium mobile project where I want to make one global function which I can use throughout the application. For that I have created other .JS file where I have defined the function and I am including that .JS file where I need to use this function and I am successfully able to call the function.
But My question is :
Can I create new Window in that function? As I have added one Label and one MapView in that window but it is not showing, while at the start of function I have added alert('FunctionCalled'), it is showing me alert but not showing me the label I have added in the window.
So anybody can help me to find out whether we can open window through function. If yes then any sample example, so that I can find out what mistake I am making.
Thanks,
Rakesh Gondaliya

you approach CAN work but is not a best practice, you should create a global namespace, add the function to that namespace and then only include the file with the function once in app.js
// apps.js
var myApp = {};
Ti.include('global.js','ui.js');
myApp.ui.openMainWindow();
then we create a seperate file for our ui functions
//ui.js
(function(){
var ui = {};
ui.openMainWindow = function() {
// do open window stuff
// call global function
myApp.global.globalFunction1();
}
myApp.ui = ui;
})();
here is where we create our global functions, we will not have to include the file everywhere since we are adding it to our global namespace
//global.js
(function(){
var global = {};
global.globalFunction1 = function() {
// do super global stuff
}
myApp.global = global;
})();
this is a simple outline of how it can be implemented, I have a complete code listing on my blog

Yes you can create a new window or add a label or anything else. If you wanted to add a label to the current window then you would do:
var helloWorld = Ti.UI.createLabel({ text: "Hello World", height: "auto", width: 200 });
Ti.UI.currentWindow.add(helloWorld);
It won't matter where the code is executing because Ti.UI.currentWindow will be the active window regardless.

Related

Titanium/ Alloy: Add event listener to a window

I have the following code in index.js:
var win = Alloy.createController('foo').getView();
win.open();
win.addEventListener('exampleEvent', function () {
Ti.API.info('Event Run!'); // does not seem to run
});
on foo.js I have the following:
function runEvent() {
$.trigger('exampleEvent');
$.getView().close();
}
// execute runEvent() somewhere later
However, the function in the event listener does not seem to run.
What am I doing wrong?
You are missing a point that custom events can only be added on a controller, not on the view.
var win = Alloy.createController('foo').getView();
In this line, you are holding the view by using getView() in win variable.
Now, it should be like this:
var win = Alloy.createController('foo');
win.on('exampleEvent', function () {
Ti.API.info('Event Run!'); // it will run now as you have added custom event on controller (means $ in .js file) itself.
});
// now you can get the top-most view (which is a window in this case) and can further use open() method on window
win.getView().open();
foo.js will remain same:
function runEvent() {
$.trigger('exampleEvent');
$.getView().close();
}
// execute runEvent() somewhere later
In my case, i was using
var controller = Alloy.createController('myController');
controller.addEventListener("customEvent",function(){});
I've been smacking my head for the last hour...
on top of what #PrashantSaini presented, there s no addEventListener on controller objects, controllers have the on function, so it should be :
controller.on("customEvent",function(){});
update
My answer is a heads up for the fact that there no addeventlistener on controller object.

dojo JsonRest call not working

I'm trying to call my RESTful service from dojo. All I can see from debugger is, it tries to call the service but it doen't reach there. There are no errors. I can see the 'hello' alert.
define(["dojo/store/JsonRest","dojo/domReady!"],
function(JsonRest){
alert("Hello");
var rest = new JsonRest({
target: "/my/rest/call"
});
}
);
I's following this page from dojotoolkit.
But if i call using a declare then it works.
define(["dojo/store/JsonRest","dojo/_base/declare","dojo/domReady!"],
function(JsonRest, declare){
var rest = declare(JsonRest);
var restResult = new rest({
target: "/my/rest/call"
});
}
);
What am I doing wrong here?
error messages in console:
You're not following that tutorial to the letter. The difference is that you're using define and not require. Dojo's define is used in combination with declare to create new Dojo classes. Dojo's require is used to load and use existing classes. The link below is a recommended read and in your case pay special attention to the 'Requiring modules' and 'Defining modules' parts:
https://dojotoolkit.org/documentation/tutorials/1.8/modules/
If you use require like in that tutorial, it works perfectly:
require([
'dojo/store/JsonRest',
], function(
JsonRest
) {
new JsonRest({
target: 'some/resource/'
}).get(1).then(function (item) {
alert(JSON.stringify(item));
});
});
Here's a working example on Plunker: http://plnkr.co/edit/ZhsO67BFpWB5Txqy0Zl9?p=preview

How to use data entered in panel in a Google Doc - GAS

First of all: this site has been a great help already to me, thnx a lot!
In a Google doc I am adding a vertical panel to assist the user in composing and sending a letter. I used the example in this thread and it works fine showing the panel:
function onOpen() {
var app = UiApp.createApplication().setWidth(455).setTitle('User input')
var panel = app.createVerticalPanel().setStyleAttribute('padding','25px')
var label1 = app.createLabel('Your name please');
var box1 = app.createTextBox().setId('Field1').setName('Field1');
panel.add(label1)
panel.add(box1)
var pasteHandler = app.createServerChangeHandler('readTextbox');
pasteHandler.addCallbackElement(panel);
var clickButton=app.createButton('OK').setId('PasteTest').addClickHandler(pasteHandler)
panel.add(clickButton);
app.add(panel);
DocumentApp.getUi().showSidebar(app);
//I want to arrive here only after a value is entered in the panel
// ... follows more code ...
}
function readTextbox(e){
var app = UiApp.getActiveApplication();
var boxValue=e.parameter.Field1;
//how to get this e.parameter values (more than one..) to the main function
return app;
}
My question is: how to make the main function wait after 'showSidebar' until a value is entered?
Second question: how to use this input outside the handler, e.g. for writing in the document? I found a workaround by writing the fields to a spreadsheet within the handler, but that's not very elegant ;-)
Many thanks in advance...
You can't make the onOpen() function wait, but you don't need to. You have a click handler and the readTextbox() function. And you don't need to get the readTextbox() function to branch back to the onOpen() function. If there are conditions that require branching to different functions depending on what the user does, then you can create a new function.
You can call a function from a function just by using it's name, and parenthesis after the name and a semicolon.
function readTextbox(e){
var app = UiApp.getActiveApplication();
var boxValue=e.parameter.Field1;
anotherCoolFunction(boxValue);
//how to get this e.parameter values (more than one..) to the main function
return app;
}
function anotherCoolFunction(someArg){
Logger.log('Some Arg: ' + someArg);
}
In the above code, after the name is entered and the user clicks the button, the readTextBox function runs, then the readTextBox() function calls the anotherCoolFunction(boxValue); function and passes the variable boxValue to the anotherCoolFunction().
You can verify that it works, by looking at the log. Choose the View Menu, and the Logs menu item to display the Log output.

how to reach to a variable in another js file in appcelerator alloy

I have a small problem.
I have index.js
var loc = require('location');
function doClick (){
loc.doIt();
}
in location.js I have these
var dee = 12;
exports.doIt = function() {
alert(dee);
};
Which means that when I click on the button I can get the alert, however, I want to reach these information without a need of click - onLoad - besides I want to return two values not only one.
How I can fix this maybe it has really an easy solution but because I have been working for a while my mind stopped working :)
regards
you should move your location.js to inside app/lib (as module). for example :
// app/lib/helper.js
exports.callAlert = function(text) {
alert('hello'+ text);
}
and then call it in your controller like this :
var helper = require("helper"); // call helper without path and .js extension
helper.callAlert('Titanium');
and your problem should be solved :)

How to structure a complex web app with RequireJS

I saw there is somes questions related to mine (like this interesting one), but what I wonders is how to do it correctly, and I couldn't find it via the others questions or the RequireJS documentation.
I'm working on a quite heavy web application that will run in only one html page.
Before RequireJS, I used to do a lot of JS modules with public methods and connecting them via the on event on the Dom READY method, like this :
var DataList = function () {
this.base = arguments[0];
this.onUpdate = function (event) { ... }
}
$(function () {
var dataList = {}; DataList.apply(dataList, [$('#content')]);
$('table.main', dataList.base).on ('update', dataList.onUpdate);
});
With RequireJS, I can easily see that I can split DataList and all others classes like this on individual files, but what about the $(function () {}); part?
Can I still keep it this way, but instead of the DOM ready function of jQuery, I put the events on the main function() of the RequireJS, when my primary libs are loaded?
Or do I have to change the way I create JS "classes", to include a init function maybe, that will be called when I do a, for example :
require(['Datalist'], function(dataList) {
dataList.init($('#content'));
});
What annoys me the most is that since I have only one html file, I'm afraid the require() will have to load a huge list of files, I'd prefer it to load just libs that, them, would load sub libs required to work.
I don't know, the way of thinking with RequireJS lost me a bit :/
How would you do?
"Can I still keep it this way, but instead of the DOM ready function of jQuery, I put the events on the main function() of the RequireJS, when my primary libs are loaded?"
If you separate the functions or 'classes' into modules then you can use the RequireJS domReady function:
require(['module1'], function(module1) {
domReady(function(){
// Some code here ftw
})
});
The benefit here is the domReady function will allow downloading of the modules instantly but won't execute them until your DOM is ready to go.
"Or do I have to change the way I create JS "classes", to include a init function maybe, that will be called when I do a, for example"
You won't need to change the way you interact with your code this way, but you can probably improve it. In your example I would make DataList a module:
define(function(require) {
var $ = require('jquery');
var DataList = function () {
this.base = arguments[0];
};
DataList.prototype.onUpdate = function() {
};
return DataList;
});
require(['data-list'], function(DataList) {
var data = {};
// Call DataList with new and you won't need to set the context with apply
// otherwise it can be used exactly as your example
new DataList(data);
});
"What annoys me the most is that since I have only one html file, I'm afraid the require() will have to load a huge list of files, I'd prefer it to load just libs that, them, would load sub libs required to work."
Make your code as modular as you want/can and then use the optimiser to package it into one JS file.