PDA

View Full Version : Dynamically instantiate a class



bkraut
27 Sep 2009, 1:42 PM
Hi,

I use metagrid, where on double click I have to retrieve from server which form to display. The case is that I have to dynamically instantiate a Form from a retrieved string.

I tried with:


var className = 'FormName';
var form = new className();

but this does not work.
How can I do it?

27 Sep 2009, 6:27 PM
try new window[className];




myClass = function() {
alert('myClass.constructor called!');
}

var someClassName = 'myClass';

new window[someClassName]()

bkraut
27 Sep 2009, 10:48 PM
Thanks - I tried, but I had no success.

See the following.



myClass = function() {
alert('myClass.constructor called!');
}
var someClassName = 'myClass';
new window[someClassName]() // This works

var win1 = new Ext.ux.PostBookWindow(); // this works !!!
var clazzName = 'Ext.ux.PostBookWindow'; // this does not work !!!
win = new window[clazzName]();

evant
27 Sep 2009, 10:55 PM
No, because you don't have a class name called 'Ext.ux.PostBookWindow'.

If you want to do dynamic classes, register xtypes for the class then use Ext.create().

StuartAshworth
28 Sep 2009, 12:48 AM
Have a look at this question on StackOverflow...

http://stackoverflow.com/questions/1216782/object-type-determined-at-runtime-javascript-extjs

Animal
28 Sep 2009, 1:44 AM
Thanks - I tried, but I had no success.

See the following.



myClass = function() {
alert('myClass.constructor called!');
}
var someClassName = 'myClass';
new window[someClassName]() // This works

var win1 = new Ext.ux.PostBookWindow(); // this works !!!
var clazzName = 'Ext.ux.PostBookWindow'; // this does not work !!!
win = new window[clazzName]();



Think about it.

"." is significant in Javascript. The function is not referenced by a property in the window object named "Ext.ux.PostBookWindow"

You have to access the property window["Ext"], and then subscript that with ["ux"], and subscript the result of that with "PostBookWindow".

You will have to have a little function which splits the string on "." and walks down the namespace.

28 Sep 2009, 2:01 AM
I think using an XType is much simpler, as Evan pointed out.

you could use Ext.ComponentMgr.create({
yourCustomXType
});

bkraut
28 Sep 2009, 3:13 AM
Thanks guys. This solves a thing perfectly.

Ext.ComponentMgr.create({
yourCustomXType
});