473,659 Members | 3,348 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Advanced javascript - can anyone explain this intricacy?

Hi - I'm new to javascript and I was reading the book Javascript
Professional Projects - there is a fragment that has me a little
perplexed, and I was wondering if anyone could explain why and how it
works.
How is it that setting a property to null alters another property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.

Can you attach "hooks" in javascript that get called whenever a
property is modified?
Or does an eventhandler get triggered behind the scenes that updates
selectedIndex - and if so - how do i attach similar eventhandlers to
objects - or is this an intrinsic feature of javascript?

Here is the function. I have inserted some debug messages which
illustrate that as soon as the property is set to null -
fromSelect.sele ctedIndex gets updated.
function swapSelects( fromSelect, toSelect )
{
var toSelect_Length = toSelect.option s.length;
while( fromSelect.sele ctedIndex -1 )
{
var index = fromSelect.sele ctedIndex;
alert( "1>" + fromSelect.sele ctedIndex );
toSelect.option s[toSelect_Length] = new Option(
fromSelect.opti ons[index].text );
toSelect.option s[toSelect_Length].value =
fromSelect.opti ons[index].value;
alert( "2>" + fromSelect.sele ctedIndex );

// note this is the line that triggers the update
fromSelect.opti ons[index] = null;
alert( "3>" + fromSelect.sele ctedIndex );

toSelect_Length ++;
}

thanks in advance.
Faisal Vali.

Sep 17 '06 #1
11 1803

Faisal Vali wrote:
Hi - I'm new to javascript and I was reading the book Javascript
Professional Projects - there is a fragment that has me a little
perplexed, and I was wondering if anyone could explain why and how it
works.
How is it that setting a property to null alters another property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.
I've tried to recreate this, but I can not. Please see the code on this
page:

http://www.krubner.com/testJavascript.htm

Sep 17 '06 #2

Faisal Vali wrote:
Hi - I'm new to javascript and I was reading the book Javascript
Professional Projects - there is a fragment that has me a little
perplexed, and I was wondering if anyone could explain why and how it
works.
How is it that setting a property to null alters another property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.
You'll note that in the experiment that I posted here:

http://www.krubner.com/testJavascript.htm

things work as you would expect: it is the value that becomes null, not
the index.

I'm not clear on how you concluded that "How is it that setting a
property to null alters another property?"

I don't see that happening.

Sep 17 '06 #3

Faisal Vali wrote:
Here is the function. I have inserted some debug messages which
illustrate that as soon as the property is set to null -
fromSelect.sele ctedIndex gets updated.
function swapSelects( fromSelect, toSelect )
{
var toSelect_Length = toSelect.option s.length;
while( fromSelect.sele ctedIndex -1 )
{
var index = fromSelect.sele ctedIndex;
alert( "1>" + fromSelect.sele ctedIndex );
toSelect.option s[toSelect_Length] = new Option(
fromSelect.opti ons[index].text );
toSelect.option s[toSelect_Length].value =
fromSelect.opti ons[index].value;
alert( "2>" + fromSelect.sele ctedIndex );

// note this is the line that triggers the update
fromSelect.opti ons[index] = null;
alert( "3>" + fromSelect.sele ctedIndex );

toSelect_Length ++;
}
I'm trying to make this function work on this page:

http://www.krubner.com/testJavascript.htm

The code is dying on the line where you reference fromSelect.opti ons.
It is hard for me to imagine what kind of parameters you're trying to
pass in to this function. The parameters seem to be complex objects
that are both arrays themselves and also contain arrays. Had you gone
into more detail, that would have been helpful. I tried to guess what
kind of objects you were using as parameters, but I've given when I
realized the complexity of these things.

For now I get this error:

Error: fromSelect.opti ons has no properties
Please note, I also had to explicitly assign a value of "0" to
fromSelect.sele ctedIndex to get even as far as I did.

Sep 17 '06 #4
Faisal Vali wrote:
Hi - I'm new to javascript and I was reading the book
Javascript Professional Projects - there is a fragment
that has me a little perplexed, and I was wondering if
anyone could explain why and how it works.

How is it that setting a property to null alters another
property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.
There was once a time when the browser's object model and JavaScript(tm)
where virtually the same thing. Standardisation has acted to separate
the two, and we now have a core language (specified by ECMA 262 3rd
Edition), vendor specific extensions to that language, and the object
model provided by the host of the scripts. This allows a standardised
javascript to be used for scripting more types of host than just web
browser (such as PhotoShop from version 7).

Assuming the above - optionObject - is a reference to the DOM
representation of an HTML SELECT element (which is necessary to explain
the phenomenon described) the behaviour of the object when it is
modified is not determined by javascript at all. It is what is
classified as a "host object", and so is not part of the language.

For the DOM representation of a SELECT element (without the MULTIPLT
attribute) the - selectedIndex - property is the index value of the
currently selected OPTION element. The act of assigning - null - to a
member of the SELECT element's - options - collection is to remove that
OPTION element from the SELECT element. And if you remove the currently
selected OPTION element it can no longer be the currently selected
OPTION element, so the - selectedIndex - property of the SELECT element
must be changed.

As an OPTION element should not become selected unless the user selects
it the - selected Index - property must be set to a value that is not an
index of an OPTION element, and one that can be used to signal to
scripts that no OPTION element is selected. The value of -1 is used for
that purpose.
Can you attach "hooks" in javascript that get called
whenever a property is modified?
<snip>

In the standardised core of javascript you cannot. As a result it is
extremely unlikely that cross-browser code would ever attempt to do so.
However, some implementations have a - watch - extension that could be
used in that way, and the JavaScript(tm) implementation has -
__defineGetter_ _ - and - __defineSetter_ _ - extension that can allow
code to react to property changes. JScritp in IE has none of these, but
some of the IE browser's host objects support an - onpropertychang e -
event handler that can be triggered by some property changes.

For pure javascript objects it is possible to adopt a design pattern
that provides 'setter' functions and insists that they are exclusively
used to set the values of properties. This allows side-effect code to be
triggered in response to changes in those property values, and it is
possible to then implement event handlers on javascript objects and have
them triggered by the side-effect code in the 'setters'.

Richard.
Sep 17 '06 #5

Faisal Vali wrote:
Can you attach "hooks" in javascript that get called whenever a
property is modified?
Or does an eventhandler get triggered behind the scenes that updates
selectedIndex - and if so - how do i attach similar eventhandlers to
objects - or is this an intrinsic feature of javascript?
I don't believe there is an event handler for a change of properties,
though you could use javascript closures to enforce such a thing:

objectForSettin gUserNumbers = function setNumberOfUser s(numberOfUsers )
{
var howManyUsersOnT hisPage = 0;

var controllerForHo wManyUsers = function(users) {
howManyUsersOnT hisPage = users;
alert("howManyU sersOnThisPage now equals " +
howManyUsersOnT hisPage);
}

controllerForHo wManyUsers(numb erOfUsers);
return controllerForHo wManyUsers;
}

This sets howManyUsersOnT hisPage to 8 :

objectForSettin gUserNumbers(8) ;
The variable howManyUsersOnT hisPage is now completely encapsulated,
like a private class variable in any object oriented language - there
is no way to reach it accept through the method we've allowed. Thus,
yes, here you could set triggers that go off whenever someone tries to
reach this value.

I put this code up on the same test page as before:

http://www.krubner.com/testJavascript.htm

Sep 17 '06 #6

Jake Barnes wrote:
Faisal Vali wrote:
Can you attach "hooks" in javascript that get called whenever a
property is modified?
Or does an eventhandler get triggered behind the scenes that updates
selectedIndex - and if so - how do i attach similar eventhandlers to
objects - or is this an intrinsic feature of javascript?

I don't believe there is an event handler for a change of properties,
though you could use javascript closures to enforce such a thing:

Actually, this would be more flexible than my first example:

function setNumberOfUser s()
{
var howManyUsersOnT hisPage = 0;

var controllerForHo wManyUsers = function(users) {
howManyUsersOnT hisPage = users;
alert("howManyU sersOnThisPage now equals " +
howManyUsersOnT hisPage);
}
return controllerForHo wManyUsers;
}
objectForSettin gUserNumbers = setNumberOfUser s();

Now objectForSettin gUserNumbers is a reference to the anonymous
function stored in controllerForHo wManyUsers. You can continue to
change the value of howManyUsersOnT hisPage, but only using this one
method:

This sets howManyUsersOnT hisPage to 8 :

objectForSettin gUserNumbers(8) ;

or 18:

objectForSettin gUserNumbers(18 );
The variable howManyUsersOnT hisPage is now completely encapsulated,
like a private class variable in any object oriented language - there
is no way to reach it accept through the method we've allowed. Thus,
yes, here you could set triggers that go off whenever someone tries to
reach this value.

I put this code up on the same test page as before:

http://www.krubner.com/testJavascript.htm
Sep 18 '06 #7

Faisal Vali wrote:
Hi - I'm new to javascript and I was reading the book Javascript
Professional Projects - there is a fragment that has me a little
perplexed, and I was wondering if anyone could explain why and how it
works.
How is it that setting a property to null alters another property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.

Can you attach "hooks" in javascript that get called whenever a
property is modified?
Or does an eventhandler get triggered behind the scenes that updates
selectedIndex - and if so - how do i attach similar eventhandlers to
objects - or is this an intrinsic feature of javascript?

Here is the function. I have inserted some debug messages which
illustrate that as soon as the property is set to null -
fromSelect.sele ctedIndex gets updated.
function swapSelects( fromSelect, toSelect )
{
var toSelect_Length = toSelect.option s.length;
while( fromSelect.sele ctedIndex -1 )
{
var index = fromSelect.sele ctedIndex;
alert( "1>" + fromSelect.sele ctedIndex );
toSelect.option s[toSelect_Length] = new Option(
fromSelect.opti ons[index].text );
toSelect.option s[toSelect_Length].value =
fromSelect.opti ons[index].value;
alert( "2>" + fromSelect.sele ctedIndex );

// note this is the line that triggers the update
fromSelect.opti ons[index] = null;
alert( "3>" + fromSelect.sele ctedIndex );

toSelect_Length ++;
}

thanks in advance.
Faisal Vali.
In javascript -1 equates to null, and null can equate to false.

What happens is you set the selected object to a null, so when you ask
it for the selected index, it returns you -1 (null which will also
equate to false).

Sep 18 '06 #8

Tom Cole wrote:
Faisal Vali wrote:
Hi - I'm new to javascript and I was reading the book Javascript
Professional Projects - there is a fragment that has me a little
perplexed, and I was wondering if anyone could explain why and how it
works.
How is it that setting a property to null alters another property?
For example setting
optionObject.op tions[optionObject.se lectedIndex] = null;
seems to set optionObject.se lectedIndex to -1 automagically.
[...]
>
In javascript -1 equates to null, and null can equate to false.

What happens is you set the selected object to a null, so when you ask
it for the selected index, it returns you -1 (null which will also
equate to false).
You should have read Richard's response. An HTML select element is not
a built-in JavaScript object, it is provided by the host environment.
In most browsers, its behaviour conforms to the W3C DOM HTML
specification which says that if no option is selected, the
selectedIndex property should return -1.

<URL: http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-85676760 >

In JavaScript, -1 is not equivalent to 'null'. When evaluated in a
conditional expression it is type converted to boolean true. According
to the ECMAScript Specification section 9.2, the numbers +0, -0 and NaN
type convert to false, any other number converts to true.

Try it:

alert( !!(-1) ); // Shows true
The fun part here is working out what should happen when the
selectedIndex property is set to null. According to the W3C
specification, the selectedIndex property is a long, which in
JavaScript equates to a number primitive. When converting 'null' to a
number using toNumber, null should be converted to +0.

It might therefore be argued that assigning null to the selectedIndex
property should result in it being set to +0, thereby making the first
option selected. Clearly that logic is flawed... :-)
--
Rob

Sep 18 '06 #9
RobG wrote:
Tom Cole wrote:
<snip>
>In javascript -1 equates to null, and null can equate to false.
<snip>
In JavaScript, -1 is not equivalent to 'null'. When evaluated in a
conditional expression it is type converted to boolean true.
<snip>
It might therefore be argued that assigning null to the selectedIndex
property should result in it being set to +0, thereby making the first
option selected. ...
Fortunately the posted code never did assign null to the -
selectedIndex - property so null's type-converting to numeric zero is
not significant.

Richard.

Sep 19 '06 #10

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

Similar topics

5
2022
by: Robert Peake | last post by:
Hi, I notice a strange behavior in PHP4 and wonder if anyone can explain it. Essentially, when I extend a class from a built-in module, I can add and access variables but can not access new functions I create within the extended class. This has only happened attempting to extend classes from ming, but I suspect it may be a universal problem (?).
5
2675
by: Sue | last post by:
After finishing up my first quarter JavaScript on 12/12/03, I decided to improve character checking on my project. In my project I only had to do very basic validation. Therefore, I only had one function to verify the name fields, age, email and gender. My question is: if I create a function for each field like the code below, what would be the best way to organize the functions and call them? Would I need one main function and place...
53
5690
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
104
16929
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from that array Could you show me a little example how to do this? Thanks.
0
8747
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.