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

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

Related

MVVM pattern in NativeScript - how to use one?

The Problem
I just cannot figure out the view model in NativeScript
I am having a hard time understanding how view-models work in NativeScript. I understand the high level concept - that the MVVM pattern allows us to create observable objects - and our UI is updated when values change.
Here is a simple example:
main-page.js
var createViewModel = require("./main-view-model").createViewModel;
function onNavigatingTo(args) {
var page = args.object;
page.bindingContext = createViewModel();
}
exports.onNavigatingTo = onNavigatingTo;
main-view-model.js
var Observable = require("tns-core-modules/data/observable").Observable;
function getMessage(counter) {
if (counter <= 0) {
return "Hoorraaay! You unlocked the NativeScript clicker achievement!";
} else {
return counter + " taps left";
}
}
function createViewModel() {
var viewModel = new Observable();
viewModel.counter = 42;
viewModel.message = getMessage(viewModel.counter);
viewModel.onTap = function() {
this.counter--;
this.set("message", getMessage(this.counter));
}
return viewModel;
}
exports.createViewModel = createViewModel;
I understand , some what, what is happening. But not everything.
Questions I Have ...
How would you add a new function , for instance, an email validation function? Would it go into the View Model page, or just plain Javscript page?
Let's say I added a new textfield to the UI. I have a tap function. Where does my function go?
So in this case, everything related to the UI should go in the createViewModel function? Is that correct?
I have also seen in sample apps, where the developer doesn't use view models at all - it appears he just creates it as an observable object.
Thank you for looking. I know I am close to understanding, but that bindingContext and the viewmodel has me a bit confused. [ I have read everything in NS docs ]
John
The answer is either of it should work. You may put the validation or tap function in view model or in the code behind file, it's upto you to decide which works best for you.
If you put it in the view model, you will use event binding (tap="{{ functionName }}" Or if you put it in code behind file, you will just export the function name and simply refer the function name on XML (tap="functionName").
By giving this flexibility you are allowed to separate your code, keep the files light weighted.

Organizing JS code with Alloy and CommonJS in Titanium projects

I'm learning with Titanium to make iPhone/Android apps. I'm using Alloy MVC framework. I never used javascript before, apart from simple scripts in HTML to access the DOM or something like that, so I never needed to structure the code before.
Now, with Titanium, I must use a lot of JS code and I was looking for ways to structure my code. Basically I found 3 ways to do it: prototype, namespace and functions inside functions.
Simple example for each:
Prototype:
NavigationController = function() {
this.windowStack = [];
};
NavigationController.prototype.open = function(windowToOpen) {
//add the window to the stack of windows managed by the controller
this.windowStack.push(windowToOpen);
//grab a copy of the current nav controller for use in the callback
var that = this;
windowToOpen.addEventListener('close', function() {
if (that.windowStack.length > 1)
{
that.windowStack.pop();
}
});
if(Ti.Platform.osname === 'android') {
windowToOpen.open();
} else {
this.navGroup.open(windowToOpen);
}
};
NavigationController.prototype.back = function(w) {
//store a copy of all the current windows on the stack
if(Ti.Platform.osname === 'android') {
w.close();
} else {
this.navGroup.close(w);
}
};
module.exports = NavigationController;
Using it as:
var NavigationController = require('navigator');
var navController = new NavigationController();
Namespace (or I think is something like that, coz the use of me = {}):
exports.createNavigatorGroup = function() {
var me = {};
if (OS_IOS) {
var navGroup = Titanium.UI.iPhone.createNavigationGroup();
var winNav = Titanium.UI.createWindow();
winNav.add(navGroup);
me.open = function(win) {
if (!navGroup.window) {
// First time call, add the window to the navigator and open the navigator window
navGroup.window = win;
winNav.open();
} else {
// All other calls, open the window through the navigator
navGroup.open(win);
}
};
me.setRightButton = function(win, button) {
win.setRightNavButton(button);
};
me.close = function(win) {
if (navGroup.window) {
// Close the window on this nav
navGroup.close(win);
}
};
};
return me;
};
Using it as:
var ui = require('navigation');
var nav = ui.createNavigatorGroup();
Functions inside functions:
function foobar(){
this.foo = function(){
console.log('Hello foo');
}
this.bar = function(){
console.log('Hello bar');
}
}
// expose foobar to other modules
exports.foobar = foobar;
Using it as:
var foobar = require('foobar').foobar
var test = new foobar();
test.bar(); // 'Hello bar'
And now my question is: which is the better to maintain code clean and clear? It seems that prototype is clear an easy to read/mantain. Namespace confuses me a bit but only needs to execute the initial function to be "available" (no use of new while declaring it, I suppose because it returns the object?namespace? "me"). Finally, functions inside functions is similar to the last, so I don't know exactly the difference, but is useful to export only the main function and have all the inside functions available for use it later.
Maybe the last two possibilities are the same, and I'm messing concepts.
Remember that I'm searching for a good way to structure the code and have functions available to other modules and also inside the own module.
I appreciate any clarification.
In the examples that they release, Appcelerator appears to follow the non-prototype approach. You can see it in the examples they have released: https://github.com/appcelerator/Field-Service-App.
I've seen a lot of different approaches to structuring applications in Titanium before Alloy. Since Alloy, I've found following the development team's examples helpful to me.
With that being said, it seems to me that all of this is still under interpretation and open to change and community development. Before Alloy there were some great community suggestions on structuring an app and I believe that it is still open with Alloy. Often when I find someone's example code I see something they did with it that appears to organize it a bit better than I thought of. It seems to make it a bit easier.
I think you should structure your application in a way that makes sense to you. You may stumble on to a better and easier way of developing applications with Alloy, because you are looking at it critically.
I haven't found a lot of extensive Alloy examples, but Field-Service-App makes sense to me. They have a nice separation of the elements in the application beyond MVC. Check it out.

Exception Error: chrome://app/content/app1.js - EXPORTED_SYMBOLS is not an array

"EXPORTED_SYMBOLS is not an array" Exception flagged when tried to use Components.utils.import("chrome://app/content/app1.js");.
I have a XUL application created and from one of the JS File(say app.js) I tried to include the other JS File as shown above.
Both app.js and app1.js are placed in content folder and also in chrome.manifest file following line is added
"content app content/"
In other JS File (app1.js), I have exported symbols like
var EXPORTED_SYMBOLS = ["Fooinstance"];
var Fooinstance = {
foo: function() {
...
}
}
In app.js,
Components.utils.import("chrome://app/content/app1.js");
// Error: chrome://app/content/app1.js - EXPORTED_SYMBOLS is not an array
...
Fooinstance.foo();
I am running this XUL app on XULRunner 17.0.1 win32 libraries.
I looked through the code in this link https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using
It did not help and if I include it as resource it works however I do not want to include it as part of resource.
Could you someone point out what mistake would be ?
I had this same problem, and I solved it:
1) changing the file extension (.js) by .jsm
2) Adding a first line on your module exporting classes to share. EG:
var EXPORTED_SYMBOLS = ["Xobject"];
function Xobject(){
}
Xobject.prototype.stop = function() {
return 'stop';
}
Xobject.prototype.run = function() {
return 'running';
}
3) Calling this way
Components.utils.import('resource://gre/modules/Services.jsm' );
Components.utils.import("chrome://myFirstAddOn/content/Xobject.jsm");
var myXobject = new Xobject();
alert(myXobject.run());
Hope it help u
For anyone else getting this, another possible reason is a circular dependency. My case was a little different, but I had two JSM files each using Components.utils.import to import each other. Then I got this error in one of them.

Yii renderpartial (proccessoutput = true) Avoid Duplicate js request

Im creating a site who works with ajaxRequest, when I click a link, it will load using ajaxRequest. When I load for example user/login UserController actionLogin, I renderPartial the view with processOUtput to true so the js needed inside that view will be generated, however if I have clientScriptRegister inside that view with events, how can I avoid to generate the scriptRegistered twice or multiple depending on the ajaxRequest? I have tried Yii::app()->clientScript->isSCriptRegistered('scriptId') to check if the script is already registered but it seems that if you used ajaxRequest, the result is always false because it will only be true after the render is finished.
Controller code
if (Yii::app()->request->isAjaxRequest)
{
$this->renderPartial('view',array('model'=>$model),false,true);
}
View Code
if (!Yii::app()->clientScript->isScriptregistered("view-script"))
Yii::app()->clientScript->registerScript("view-script","
$('.link').live('click',function(){
alert('test');
})
");
If I request for the controller for the first time, it works perfectly (alert 1 time) but if I request again for that same controller without refreshing my page and just using ajaxRequest, the alert will output twice if you click it (because it keeps on generating eventhough you already registered it once)
This is the same if you have CActiveForm inside the view with jquery functionality.. the corescript yiiactiveform will be called everytime you renderPartial.
To avoid including core scripts twice
If your scripts have already been included through an earlier request, use this to avoid including them again:
// For jQuery core, Yii switches between the human-readable and minified
// versions based on DEBUG status; so make sure to catch both of them
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
If you have views that are being rendered both independently and as HTML fragments to be included with AJAX, you can wrap this inside if (Yii::app()->request->isAjaxRequest) to cover all bases.
To avoid including jQuery scripts twice (JS solution)
There's also the possibility of preventing scripts from being included twice on the client side. This is not directly supported and slightly more cumbersome, but in practice it works fine and it does not require you to know on the server side what's going on at the client side (i.e. which scripts have been already included).
The idea is to get the HTML from the server and simply strip out the <script> tags with regular expression replace. The important point is you can detect if jQuery core scripts and plugins have already been loaded (because they create $ or properties on it) and do this conditionally:
function stripExistingScripts(html) {
var map = {
"jquery.js": "$",
"jquery.min.js": "$",
"jquery-ui.min.js": "$.ui",
"jquery.yiiactiveform.js": "$.fn.yiiactiveform",
"jquery.yiigridview.js": "$.fn.yiiGridView",
"jquery.ba-bbq.js": "$.bbq"
};
for (var scriptName in map) {
var target = map[scriptName];
if (isDefined(target)) {
var regexp = new RegExp('<script.*src=".*' +
scriptName.replace('.', '\\.') +
'".*</script>', 'i');
html = html.replace(regexp, '');
}
}
return html;
}
There's a map of filenames and objects that will have been defined if the corresponding script has already been included; pass your incoming HTML through this function and it will check for and remove <script> tags that correspond to previously loaded scripts.
The helper function isDefined is this:
function isDefined(path) {
var target = window;
var parts = path.split('.');
while(parts.length) {
var branch = parts.shift();
if (typeof target[branch] === 'undefined') {
return false;
}
target = target[branch];
}
return true;
}
To avoid attaching event handlers twice
You can simply use a Javascript object to remember if you have already attached the handler; if yes, do not attach it again. For example (view code):
Yii::app()->clientScript->registerScript("view-script","
window.myCustomState = window.myCustomState || {}; // initialize if not exists
if (!window.myCustomState.liveClickHandlerAttached) {
window.myCustomState.liveClickHandlerAttached = true;
$('.link').live('click',function(){
alert('test');
})
}
");
The cleanest way is to override beforeAction(), to avoid any duplicated core script:
class Controller extends CController {
protected function beforeAction($action) {
if( Yii::app()->request->isAjaxRequest ) {
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-2.0.0.js'] = false;
Yii::app()->clientScript->scriptMap['anything.js'] = false;
}
return parent::beforeAction($action);
}
}
Note that you have to put the exact js file name, without the path.
To avoid including script files twice, try this extension: http://www.yiiframework.com/extension/nlsclientscript/
To avoid attaching event handlers twice, see Jons answer: https://stackoverflow.com/a/10188538/729324

Using Global Function in 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.