Sunday, June 2, 2024
73
rated 0 times [  76] [ 3]  / answers: 1 / hits: 44146  / 13 Years ago, mon, august 1, 2011, 12:00:00

We have a lot of setup JS code that defines panels, buttons, etc that will be used in many other JS files.



Typically, we do something like:



grid.js



var myGrid = .....


combos.js



var myCombo = .....


Then, in our application code, we:



application.js



function blah() {
myGrid.someMethod()
}


someother.js



function foo() {
myCombo.someMethod();
myGrid.someMethod();
}


So, should we be using the var myGrid or is better to use window.myGrid



What's the difference?


More From » global-variables

 Answers
4

I would suggest creating a namespace variable var App = {};



App.myGrid = ...


That way you can limit the pollution of the global namespace.



EDIT: Regarding the number of variables issue - 2 possible solutions come to mind:




  1. You can further namespace them by type(Grids, Buttons, etc) or by relationship(ClientInfoSection, AddressSection, etc)

  2. You encapsulate your methods in objects that get instantiated with the components you have



ex: you have



function foo() {
myCombo.someMethod();
myGrid.someMethod();
}


becomes:



var Foo = function(combo, grid) {
var myCombo = combo;//will be a private property
this.myGrid = grid;//will be a public property
this.foo = function() {//public method
myCombo.someMethod();
myGrid.someMethod();
}
}
App.myFoo = new Foo(someCombo, someGrid);
App.myFoo.foo();


this way you limit the amount of little objects and only expose what you need (namely the foo function)



PS: if you need to expose the internal components then add them to this inside the constructor function


[#90876] Sunday, July 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billt

Total Points: 608
Total Questions: 100
Total Answers: 87

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;