Is there Global variables in EXT JS - javascript

In java and C++ we could store a variable globally and access its value from any where in the project.
Say, i am inside a class called Residence and i am saving the residenceNumber which is a INT to a global variable called houseNumberGlobalVariable.
Now, i could access houseNumberGlobalVariable from any class in the project. In a similar fashion, is there a Global variable in EXTJS that i could use.
I need to set a value from one class and access it from another. What is the equivalent in EXT JS. I don't think there's a global variable concept in EXTJS, but what is the equivalent in it ?

Create a special class and put all your global variables there.
Ext.define('MyApp.global.Vars', {
singleton: true,
....
houseNumberGlobalVariable: undefined
});
This way if you need access for it anywhere in the code just use MyApp.global.Vars.houseNumberGlobalVariable

Just declare a variable in app.js it will act as global variable.
var globalVar;
You can add anything into that like
globalVar.myStore = yourStore;

Based on your Application you can declare your global variable.
Scenario 1 : Declare inside the config
If you are going to use getter/setter methods (i.e change the variable frequently then go for config based)
Declaring the Appconstants
Ext.define('Practice.utilities.AppConstants', {
alias: 'widget.AppConstants',
config: {
mainVarTest: 'mainVarTest',
},
testvar: 'Testing value',
foo: 'bar',
meh: 42,
constructor: function(options) {
this.initConfig(options);
}
});
Calling the variable
var AppConstants = Ext.widget("AppConstants");
console.log(AppConstants.getMainVarTest());
Scenario 2 : Declare inside Singleton class
If your application needs global variable but it wont be alter any more inside the app. This class help to load the constant variable only once. (i.e you are not going changing the variable). This type is suits for your application
Declaring
Ext.define('Practice.utilities.AppConstants', {
alias: 'widget.AppConstants',
singleton: true,
testvar: 'Testing value',
foo: 'bar',
meh: 42,
});
Calling
var AppConstant=Practice.utilities.AppConstants;
console.log(AppConstant.foo);
Scenario 3 : Declare as Statics
Statics is static variable (exactly same as java). Advantage of using static variable is the life time of variable is indefinite longer period until explicitly cleared.
Ext.define("Practice.utilities.AppConstants", {
statics: {
mainVarTest: 'mainVarTest'
},
});

I noticed the one thing missing here was a solution from the Sencha Architect program on how to create a global variable.
Go to your "Application" node on the project Inspector. Next click in the Configs search/Filter box, this is not only for searching but for creating config entries too. When you first look at this box it will have a Smokey pre-filled text of Filter Configs... .
Enter your global variable name and you will notice nothing is found in the list below, (if the value is found in the config list then you already have this variable or your using a keyword). To the right of the text box and the lock icon is an "Add" button. Click the "Add" button to add your global variable into the application.
So lets say we have created the Foo variable at this point. You will now see an entry in your config list. To the left of this entry is an ellipses button, this is currently designating that the new variable we created is a String. Click the button and change it to something different like a 'Number' field. Enter a value for this new variable and your now done, you have a global variable.
So how do you access this newly created variable? here is a sample bit of code stuffing the global into a local variable to be used.
var bar= MyApp.app.Foo;
The 'MyApp' reference is the Application name config setting for the application you are creating. You can find this same value in the config settings of the Application node by filtering on name.

var globalVar = {}; add in your app.js file, its working fine

Related

how to use a variable only after it is set in nodejs

I am using a global variable job_name. I will set the value for this variable in file1.ts. I would like to use the global variable in file2.ts. However, in file2.ts, job_name is undefined though I am setting in file1.ts. Seems like since file1 and file2 are loaded as soon as project is initiated (even before job_name is set in file1), file2 is assuming a value of undefined for job_name. Please let me know how I can use job_name in file2.ts with the value set in file1.ts.
global.d.ts
declare global {
var job_name: any
}
export { };
Extra info for reference:
Original question (this is my actual scenario) -
Global variable for 'log' in other files is undefined since it is set after project is started in nodejs

Why can't I access my custom string prototype from an object method?

I have a custom string prototype that does some actions to a string;
String.prototype.norm_to_ascii=function(){return unescape(encodeURIComponent(this))};
In my example, the string that I want to apply the prototype to is a global object property that lives outside of the SampleObject object. In my actual code it would be referenced like this;
var userObject = {
name: "SomeName",
id: "SomeID"
}
It works everywhere in my project (other js files) except for within a particular Object method;
var SampleObject = { //This is in it's own js file called sampleobject.js
test: 0,
doStringThings {
let something = userObject.id.norm_to_ascii() //RETURNS userObject.id.norm_to_ascii is not a function
}
}
So in the SampleObject, I need to use the id, for example, but I need to do some basic decoding of the id value that is in the userObject which is what the string prototype does.
I can use this string prototype elsewhere. This is in a chrome extension so I have defined the prototype in the service worker and it can be used in the popup and content pages as well as the service worker so it must have to do with the object method but I can't figure out why?
Can anyone offer any suggestions to expose that prototype to the object method without having to redefine it?
EDIT
I should have been more clear in my explanation. I updated my example above.
You forget about this
this.otherTestValue.norm_to_ascii()
After seeing the updated question my conclusion is that you are defining the norm_to_ascii function after you run it.
Changing the order of the imports should fix the problem. Can you show us the structure of the project and where are you importing the file with that prototype?

Global variables in Meteor

I have
var Schemas = {};
Meteor.isClient && Template.registerHelper("Schemas", Schemas);
Schemas.Person = new SimpleSchema({
fullName: {
type: String,
index: 1,
optional: true,
},
email: {
type: String,
optional: true
},
address: {
type: String,
optional: true
},
isActive: {
type: Boolean,
},
age: {
type: Number,
optional: true
}
});
in one file and
var Collections = {};
Meteor.isClient && Template.registerHelper("Collections", Collections);
Persons = Collections.Persons = new Mongo.Collection("Persons");
Persons.attachSchema(Schemas.Person);
in another file.
I get the error ReferenceError: Schemas is not defined. It's rather obvious that I have to define Schemas in my collections.js file instead of having them separate. But how does Meteor work with code in separate files? I can access some objects and variables while others are unaccessible.
When you define a variable in the classic JavaScript way :
var someVar = 'someValue';
at the root of your .js file Meteor scopes it to the file using an IIFE.
If you want to define a global variable, simply don't write the var, giving :
someVar = 'someValue';
This will define a variable in all your application by default, although you may restrict it by writing that declaration in a specific recognized folder (client or server folder for example).
However this variable won't be defined absolutely first. It will be defined when Meteor runs the actual code that defines it. Thus, it may not be the best practice because you're going to struggle with load order, and it will make your code dependent on how Meteor loads files: which folder you put the file in, the name of the file... Your code is prone to messy errors if you slightly touch your architecture.
As I suggested in another closely related post you should go for a package directly!
Variables in Meteor declared with the var keyword are scoped to the file they are declared in.
If you want to create a global variable do this
Schemas = {}
ReferenceError is a Node error. Meteor is a framework on top of Node.
Node has a global scope (aka Node's global variable). This error is thrown by Node (not Meteor) if you try to access an undefined global variable.
Browsers also have a global scope called window, and do not throw ReferenceErrors when undefined variables are accessed.
Here's a pattern I like for adding functionality to a class (it's very Meteor):
/lib/Helpers.js <-- Helpers for everyone (node+browser)
/server/Helpers.js <-- Server helpers (node)
/client/Helpers.js <-- Client helpers (browser)
Consider these implementations:
// /lib/Helpers.js
Helpers = {/* functions */}; // Assigned to window.Helpers and global.Helpers
// /server/Helpers.js
Helpers = _.extend(Helpers, {/*more functions*/}
// /client/Helpers.js
Helpers = _.extend(Helpers, {/*more functions*/}
This is a trivial example. What if I didn't want to worry about load order? Why not _.extend() in /lib/Helpers.js?
// /lib/Helpers.js
// Helpers = {/* functions */}; // Overwrites...
Helpers = _.extend(Helpers, {/* functions */}); // ReferenceError
Because you'll get a ReferenceError from Node if Helpers isn't defined - specifically the "Helpers" used as an argument. (Node knows to assign Helpers as global.Helpers).
Here are two ways to "fix" this:
1) Assign Helpers to something
// /lib/Helpers.js
// Helpers = Helpers || {} // would be another ReferenceError
if (typeof Helpers === 'undefined') Helpers = {};
Helpers = _.extend(Helpers, {/* functions */});
2) Use helpers from the global
// /lib/Helpers.js
Helpers = _.extend(global.Helpers, {/* functions */}); // works in node, but...
Both of which suck.
1)'s syntax is horrible.
2) works in node, but there is no global in browsers. So it fails it's purpose.
So I gave up and went back to overwriting it the first time in lib, and looking for runtime errors if anything was overwritten.
If you have a handy cross-browser syntax for this, do comment :-)
var something = something || {}
something.blah = foo;
Here's some other JS shorthand tips.
Session variables are global and can be accessed in different files/functions easily. Session.setPersistent is used to set the variable name persistently across all files. One might restrict from using session variables when their app is too big as they don't get deleted (hence possible memory leaks) and might give error in the console (if undefined or so). Link to the docs : https://docs.meteor.com/api/session.html

How do I create a global variable in Geddy

I'm like to define a global variable box that is available in all controllers across my app in Geddy. How would one go about doing this?
You can add a global variable in: /config/secrets.json. If you don't have this secret yet it can be generate using:
geddy gen secret
And then add below to the secret.json.
{
"box": "value of box"
}
And value can be used geddy.config.box

Where to add Global variables in ExtJS MVC?

I am wondering where to add global variables for an ExtJS Application. I already looked at some suggestions in stackoverflow that mention that you can add them inside app.js. But, can anyone be more specific? My app.js looks something like this:
Ext.application({
launch: function() {..}
});
So, where exactly do the variables go? In the launch function? Outside Ext.application?
Better approach would be to create a separate class to hold such global constants. Then you should just put that constants class as requires in app.js.
Ext.define("App.Constants", {
singleton : true,
BASE_URL : "http://localhost:8080/",
LABLE_HEADER : "geekrai.blogspot",
TIMEOUT : 6000
});
This will ensure that class is loaded and now you can access any property/global value.
I have mentioned the same in detail on my blog : link
Declare your own object namespace and add them there:
Ext.ns('My.Application.Globals');
My.Application.Globals.SomeValue = 5;
My.Application.Globals.SomeText = 'Hello World!';
However globals are usually frowned upon unless absolutely needed, so try and get around using them if you can.
I know you already accepted an answer which is fine. I just wanted to add an MVC way to include namespaced variables available to the app. There is one caveat to these 'globals' - you can not use them in your class definitions. Meaning you can not reference your app in Ext.define({}) methods. They have to be use in initComponent method or later.
So here is what I do:
Ext.application({
name:'MyApp',
appFolder:'js/app',
controllers:[ 'Main' ],
autoCreateViewport : true,
launch:function () {
console.log("App Launched!");
MyApp.app = this; //added this to get reference to app instance. IMPORTANT!
},
//variables used throughout the app
globals:{
myURL:'http://example.com',
magicNum:5
}
});
To use these application wide variables you reference your app namespace and so do not pollute the global space. Like this:
MyApp.app.gloabals.magicNum
Aside from whatever features may be built into Ext, you can always use an immediate function to create a closure:
(function(){
var globalVariable = 'foo';
Ext.application({
launch: function() { alert(globalVariable); }
});
})();

Categories

Resources