Saturday 30 March 2013

How to declare global variables in Sencha Touch 2

Every Application requires to set Global Variables in order to access anywhere in your application.

For Example, Let's say if you want to set the BaseUrl and if you want to modify it, you need to modify it in one place instead of modifying more places of your application.

In Sencha Touch 2, declaring Global Variables is easy and it need to be  written inside Ext.Application. Below is the way to do it.

Ext.application({
    name: 'MyApp',     baseUrl: 'http://domainname/path/index.php',     launch:function(){} });
We have set baseUrl as the Global variable of the application. If you need to access anywhere else (let's say in Store or Model), You need to use the below code,

MyApp.app.baseUrl;

This one follows the following format {<application name>.<app folder name>.<global variable>}

if you want to test whether this works, try adding the above access code inside Ext.Msg.alert() or console.log();

Another Way of declaring Global Variable

Sencha Touch 2 also provides another way of declaring Global variables inside launch() function. Let's rewrite the above code.

Ext.application({
    name: 'MyApp',
    launch:function(){
       var baseUrl = 'http://domainname/path/index.php';
    }
});

You can access the global variable (baseUrl) like this

Ext.Msg.alert(baseUrl);

This approach has one drawback i.e you need to make sure the same baseUrl variable is not set any where else in your application.

I hope, you enjoyed this Post.

9 comments:

  1. Thanks. Very useful!

    ReplyDelete
  2. Hi,
    This too has been very helpful for me. Can you please guide how to create a global function so that it is accessible from all the controller present in the app. Can we declare as baseurl has been defined in this tutorial.
    Thank you!!

    ReplyDelete
    Replies
    1. This blog Post will solve your problem. Creation of Utility Class that contains both properties and methods. you can access these in all controllers.

      http://sureshdotariya.blogspot.in/2013/06/how-to-create-utility-class-in-sencha.html

      Thanks
      Suresh Kumar A

      Delete
  3. i have been hopeless
    if you could help me on this http://stackoverflow.com/questions/17590305/cannot-parse-nested-json-fully-sencha
    i am in great need of this.Please

    ReplyDelete
  4. Hi,
    it's the best site that i have seen on sencha.
    can you please upload a tutorial describing how switch between views in Sencha from a list.
    For ex. in the right side there will be list listing items and when clicking on items new views should open depending upon list items.

    ReplyDelete
  5. Here is the URL that will change panel data based on list item tap

    http://sureshdotariya.blogspot.in/2013/07/display-panel-data-on-list-item-tap-in.html

    Thanks
    Suresh Kumar A

    ReplyDelete