473,385 Members | 1,867 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

object's name (anti-eval)

Is in javascript a method to get object's identifier as string?
E.g., may I write function GetName thus, that

var v;
var s = GetName(v);

has led to

s == "v"

Please, help.
Jul 23 '05 #1
11 1672
Lee
Oleg Alistratov said:

Is in javascript a method to get object's identifier as string?
E.g., may I write function GetName thus, that

var v;
var s = GetName(v);

has led to

s == "v"


No. It would make no sense, since the same object can have many
different names. Also, if you think you need an object's name,
you are probably making a design mistake of some sort.

Jul 23 '05 #2
> Is in javascript a method to get object's identifier as string?
E.g., may I write function GetName thus, that

var v;
var s = GetName(v);

has led to

s == "v"


You are correct in wanting to avoid eval. Generally, an object's name is
irrelevant because you are working with object references, not object
names. If you need object names in order to avoid learning to use object
references, then you should obtain a better book. See
http://www.crockford.com/javascript/javascript.html

Names can be useful in some applications. In those cases, keep the
objects in a little database.

var database = {};
function MyObject(name) {
this.name = name;
database[name] = this;
}

So,

object.name

returns an object's name.

database[name]

returns the object.
Jul 23 '05 #3
Lee wrote:
No. It would make no sense, since the same object can have many
different names. Also, if you think you need an object's name,
you are probably making a design mistake of some sort.


Thank you!

I'll try to describe the problem as a whole. I hope, somebody may offer
the best decision.

The class Button holds properties which describes a graphic button.
Its method Button.Draw write the corresponding content:

function Button_Draw()
{
document.write(
"<div id=\"" + this.ID + "\"" +
" onclick=\"Button_Click();\">"
);
...

Several buttons are grouping in the button bar:
Bar's constructor:

function Bar(buttons)
{
this.Items = new Array(arguments.length);
for (i = 0; i < arguments.length; i++)
this.Items[i] = arguments[i];
}

In event handler Button_Click I need to get properties of Button object,
which was creating this DIV element.

If we have name of the Bar object, we may build the Button_Click calling
in that way:

"onclick=\"Button_Click('" + BarName + "', " + ButtonIndex + ");\""

This is allow using in Button_Click the following code:

function ButtonClick(BarName, ButtonIdx)
{
var t = eval(BarName).Items[ButtonIdx].Caption;
....
}

For this case I need to get object's name as string variable (BarName).

I understand that this code looks ugly, but I do not see a way to make
it better.

Please, help!
Jul 23 '05 #4
Oleg Alistratov wrote:
The class Button holds properties which describes a graphic button.
Its method Button.Draw write the corresponding content:

function Button_Draw()
{
document.write(
"<div id=\"" + this.ID + "\"" +
" onclick=\"Button_Click();\">"
);
... Change the onclick to: onclick=\"Button_Click(this);\"


Several buttons are grouping in the button bar:
Bar's constructor:

function Bar(buttons)
{
this.Items = new Array(arguments.length);
for (i = 0; i < arguments.length; i++)
this.Items[i] = arguments[i];
Also set up an object mapping button ids to buttons:

this.ButtonsById = new function(buttons) {
for (i = 0; i < buttons.length; i++)
this[buttons[i].ID] = buttons[i];
}(buttons)
}


Now all you have to do in Button_Click is use the ID to match the event to
the button:

function Button_Click(theDiv) {

var button = thebar.ButtonsById[theDiv.ID];
...

}

BTW, you would be much better to manipulate the HTML DOM directly instead
of using document.write. That would let you associate a function directly
with the event instead of having to use a text string. A function can
access variables in an outer scope when it was defined, so you can bypass
all of the id lookups and do something like:

function AssociateButtonWithDiv(div, button) {
function clicked() {
button.clicked(div);
}

if (isMozilla) {
div.addEventListener("click", clicked, false);
} else if (isIE) {
div.attachEvent("onclick", clicked);
}
}

All code samples above are untested.
Jul 23 '05 #5
Oleg Alistratov wrote:
The class Button holds properties which describes a graphic button.
Its method Button.Draw write the corresponding content:
... [and written-out content needs to refer back to its writer] ...


What I do in some of my libs at the url below is to have a global array that
stores references to objects of a certain type. Each time an object is
created, it gets a unique index as one of its properties, and adds a
reference to itself into the global array.

So, any time it needs to create a stand-alone reference to itself, it can do
something like
document.write("GlboalObjectArray[" + this.index + "].doSomething()");

There may be better ways to do it, but this works well for me.

--
Matt Kruse
http://www.JavascriptToolbox.com
Jul 23 '05 #6
Oleg Alistratov wrote:

function ButtonClick(BarName, ButtonIdx)
{
var t = eval(BarName).Items[ButtonIdx].Caption;


var t=window[BarName].......

All Global variables are properties of the window object

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #7
Duncan Booth wrote:
Now all you have to do in Button_Click is use the ID to match the event to
the button:

function Button_Click(theDiv) {

var button = thebar.ButtonsById[theDiv.ID]; ......................====== ...

}
I could found independently to such decision. The further experiments
have appeared, because it was necessary to use multiple bars in the same
document:

var button = SomethingBig.BarById[theBar.ID].ButtonsById[theDiv.ID];

I assumed to use

eval(BarName)

instead

SomethingBig.BarById[theBar.ID]

This situation has led to a problem described in the my first message.
BTW, you would be much better to manipulate the HTML DOM directly instead
of using document.write.


Thanks, it's a good idea. This approach is new to me, I'll try to
understand more in detail. Thank you!
Jul 23 '05 #8
Douglas Crockford <no****@covad.net> wrote in message news:<1e7a7
Names can be useful in some applications. In those cases, keep the
objects in a little database.

var database = {};
function MyObject(name) {
this.name = name;
database[name] = this;
}

So,

object.name

returns an object's name.

database[name]

returns the object.


Pardon the newbie question, but what does the word "this" mean here?
It seems to have a different meaning in Java and PHP.
Jul 23 '05 #9
Duncan Booth <du**********@invalid.invalid> wrote in message
BTW, you would be much better to manipulate the HTML DOM directly instead
of using document.write. That would let you associate a function directly
with the event instead of having to use a text string. A function can
access variables in an outer scope when it was defined, so you can bypass
all of the id lookups and do something like:

function AssociateButtonWithDiv(div, button) {
function clicked() {
button.clicked(div);
}

if (isMozilla) {
div.addEventListener("click", clicked, false);
} else if (isIE) {
div.attachEvent("onclick", clicked);
}
}

All code samples above are untested.


Forgive the ignorant question, but what is isMozilla? Is that a
constant that exists in Mozilla, to let you know that you're dealing
with Mozilla? Where did you find it? Can you point me to some
documentation regarding it?
Jul 23 '05 #10
lawrence wrote:
Duncan Booth <du**********@invalid.invalid> wrote in message
BTW, you would be much better to manipulate the HTML DOM directly instead
of using document.write. That would let you associate a function directly
with the event instead of having to use a text string. A function can
access variables in an outer scope when it was defined, so you can bypass
all of the id lookups and do something like:

function AssociateButtonWithDiv(div, button) {
function clicked() {
button.clicked(div);
}

if (isMozilla) {
div.addEventListener("click", clicked, false);
} else if (isIE) {
div.attachEvent("onclick", clicked);
}
}

All code samples above are untested.

Forgive the ignorant question, but what is isMozilla? Is that a
constant that exists in Mozilla, to let you know that you're dealing
with Mozilla? Where did you find it? Can you point me to some
documentation regarding it?


It falls in the same place the isIE variable falls. Its an utterly
flawed attempt to detect the browser when the browser doesn't matter.
The only way that isMozilla/isIE would be accurate in that scenario is
if its defined like this:

if(div.addEventListener) isMozilla = true;

All of it is more predictable when written something like this:

if (div.addEventListener) {
div.addEventListener("click", clicked, false);
} else if (div.attachEvent) {
div.attachEvent("onclick", clicked);
}

Even then, div might not be a good variable name.
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #11
Randy Webb wrote:
It falls in the same place the isIE variable falls. Its an utterly
flawed attempt to detect the browser when the browser doesn't matter.
Actually it falls into the category of 'I was trying to paraphrase the
sense of the code relating it to the OP's question, not give them a line
for line working solution'.
The only way that isMozilla/isIE would be accurate in that scenario is
if its defined like this:

if(div.addEventListener) isMozilla = true;

All of it is more predictable when written something like this:

if (div.addEventListener) {
div.addEventListener("click", clicked, false);
} else if (div.attachEvent) {
div.attachEvent("onclick", clicked);
}
Or possibly just check for one then assume the other. It depends whether it
is important to tell the user that the functionality they expect isn't
there, or if you just want to silently fail to provide the functionality.

Even then, div might not be a good variable name.

Nor would I expect things like 'click' to be hardwired in the final code.
Obviously proper code would have a general function for attaching events to
methods.

FWIW, the template I based the paraphrased version on is from Kupu. It also
has the broken method of testing for browser support, but it isn't so
significant in this case because Kupu explicitly only handles IE and
Mozilla (on any other browser it degrades to a textarea).

function addEventHandler(element, event, method, context) {
/* method to add an event handler for both IE and Mozilla */
var wrappedmethod = new ContextFixer(method, context);
try {
if (_SARISSA_IS_MOZ) {
element.addEventListener(event, wrappedmethod.execute, false);
} else if (_SARISSA_IS_IE) {
element.attachEvent("on" + event, wrappedmethod.execute);
} else {
throw "Unsupported browser!";
};
} catch(e) {
alert('exception ' + e.message + ' while registering an event
handler for element ' + element + ', event ' + event + ', method ' +
method);
};
};

function removeEventHandler(element, event, method) {
/* method to remove an event handler for both IE and Mozilla */
if (_SARISSA_IS_MOZ) {
window.removeEventListener('focus', method, false);
} else if (_SARISSA_IS_IE) {
element.detachEvent("on" + event, method);
} else {
throw "Unsupported browser!";
};
};

function ContextFixer(func, context) {
/* Make sure 'this' inside a method points to its class */
this.func = func;
this.context = context;
this.args = arguments;
var self = this;

this.execute = function() {
/* execute the method */
var args = new Array();
// the first arguments will be the extra ones of the class
for (var i=0; i < self.args.length - 2; i++) {
args.push(self.args[i + 2]);
};
// the last are the ones passed on to the execute method
for (var i=0; i < arguments.length; i++) {
args.push(arguments[i]);
};
self.func.apply(self.context, args);
};
};
An example of use matching the question could be:

Button.prototype.addClickHandler = function() {
var theDiv = document.getElementById(this.ID);
addEventHandler(theDiv, 'click', this.onClick, this);
}

Button.prototype.onClick = function() {
... whatever ...
}
Jul 23 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another...
6
by: sriram | last post by:
Hi, I have been seing a weird problem with db2look tool in db2 8.2 on Windows 2000 platform. When i spool the DDL using db2look, it spools the DDL in the ascending order of database objects...
5
by: | last post by:
Trying to learn about manipulating collections of objects, and populating these objects dynamically from datasources. Could someone post a code sample that shows the following: Instantiating a...
8
by: Lüpher Cypher | last post by:
Hi, Suppose we have a hierarchical class structure that looks something like this: Object | +-- Main | +-- Object1
161
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.....
7
by: RSH | last post by:
This is probably a very simple question but... How do I get the instantiated name of an object from within the class? Example: Sub main Dim c1 as new TestClass() c1.PrintName()
6
by: Martin | last post by:
Hi I need to maintain a <setof pointers to objects, and it must be sorted based on the values of pointed objects, not pointer values. I can achieve this easily by defining my own comparing...
7
by: RSH | last post by:
I am working through some design patterns, and one recurring theme for me is the need to be able to communicate between objects while promoting encapsulation and loose coupling between them. ...
14
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared...
16
by: Wayne | last post by:
I've read that one method of repairing a misbehaving database is to save all database objects as text and then rebuild them from the text files. I've used the following code posted by Lyle...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.