PDA

View Full Version : 4.1.0 with MVC: global variables and helpers in separate .js files?



jason@jnj.org
26 May 2012, 8:01 AM
Take this simple app:


Ext.application({
requires: ['Ext.container.Viewport' ],
name: 'X', appFolder: 'app', controllers: [ 'whatever' ],

launch: function() {
X.someglobal = 'foobar'
Ext.create('Ext.container.Viewport', { layout: 'fit', items: [ { xtype: 'whatever', } ],});
console.log("foobar: " + X.someglobal);
}
});


The console.log works as expected. But now I want to move "X.someglobal = 'foobar'" into its own .js file, say foobar.js. But this doesn't work:



launch: function() {
Ext.require('foobar');
Ext.create('Ext.container.Viewport', { layout: 'fit', items: [ { xtype: 'whatever', } ],});
console.log("foobar: " + X.someglobal);
}


Clearly, I'm failing to understand something here. What's the best practice for putting globals and utility functions into their own js files?

scottmartin
26 May 2012, 8:49 AM
I would vote against using globals .. you might try something like this:

stuff.js


Ext.define('MY.stuff', {
singleton: true,
someVar: 1
});


app.js


..
requires: [
'MY.stuff',
]

// access to var
MY.stuff.someVar


Regards,
Scott.

jason@jnj.org
26 May 2012, 9:02 AM
That's what I'm trying to accomplish: state variables and such under my app namespace. After I posted, I actually went and discovered the singleton method, which gets the job done.

But oddly, I'm having trouble making it work elegantly within the MVC framework. For example, this works:



// in app.js
Ext.application({
requires: ['util' ],
name: 'X', appFolder: 'app',
launch: function() {
util.setup();
console.log("Foo: " + X.foo);
...
},
});

// in util.js
Ext.define('util', {
singleton: true,
setup: function() { X.foo = "bar";}
});

But this does NOT:



// in app.js
Ext.application({
name: 'X', appFolder: 'app',
launch: function() {
Ext.require('X.util');
X.util.setup();
console.log("Foo: " + X.foo);
...
},
});

// in util.js inside the app folder
Ext.define('X.util', {
singleton: true,
setup: function() { X.foo = "bar";}
});

The first one works, but it seems a bit counter to the MVC layout idea. Ideas?

scottmartin
26 May 2012, 11:06 AM
You should provide all of your models,controller and requires before the launch.

Scott.

jason@jnj.org
26 May 2012, 4:35 PM
Pretty sure I'm losing my mind. I swear I tried that, but must have fat-fingered something. Anyway, it's working fine now. Thanks!