Franki1986
Franki1986

Reputation: 1436

create a javascript object by string

I want to access a usercontrol by a predifened name, like the DevExpress components can. Something like this:

"<dx:MyUserControl runat="server" ID="My" ClientInstanceName="MyClient"></>"

In my main page I would like to access a client method of my usercontrol. Something like:

MyClient.DoSomething();

In my usercontrol page there would be an object that implements this method:

function myClass{
    DoSomething : function(){ var a = 2 + 2;}
}

So, normally I would declare the object like : var MyClient = new myClass();

But now MyClient is dynamic, the ClientInstanceName could be whatever...

So how could I do this?

Maybe JSON or eval?

Upvotes: 0

Views: 83

Answers (1)

Optimizer
Optimizer

Reputation: 263

Your question is a bit dual meaning, so let me post answer of both the meanings that I found.

You have a variable named MyClient and a class named myClass.

Now, even if we assume both the names here are dynamic, and you get and store both the names in variables A and B, such that

if B equals "foobar" , then you are sure that there is a class on the page like

function foobar() { ... }

and if A equals "myFoobar", you know that you have to actually do something like

var myFoobar = new foobar();

Now, since both the variable and the class are globally scoped, you can easily do

window[A] = new window[B]();

and that's it!

Upvotes: 1

Related Questions