Javascript objects containing arrays - arrays are filled incorrectly

Hi all,

I am developing a point-of sale application and I have a javascript object (in literal notation) that has some properties and methods.
The outer object is called "pos", "pos" has an inner object called "display" and "display" has one or more "lines". Because there can be more that one line in the display of the pos, I'm implementing an array of lines.

Adding to them seems to be no problem, I keep track of the count and I increment the array, adding values as I go. The problem is, when I read back from the array, all the elements of the array contain only the last added value.

The attached code is a simple HTML page that demonstrates the problem. I fill the array, then read back element 2 (but this can be any element) and it contains the values of the last added element...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html>
<head>
	<title></title>
	<style type="text/css">
		@import url(/~css/main.css);
	</style>
	<script type="text/javascript">
		var pos = 
		{
			display: {
							count:0,
							selected: null,
							lines: [],
							add:	function(amount,article,price)
									{
										this.lines[this.count] = line;
										this.lines[this.count].amount=amount;
										this.lines[this.count].article=article;
										this.lines[this.count].price=price;
									this.count = this.count + 1;
									}
							}
		};
		
		var line = 
		{
			amount	: null,
			article	: null,
			price	: null,
			edit	: function(){alert('edit line')},
			clear	: function(){alert('clear line')},
			select	: function(){alert('select line')}
		}
	
	
	function test()
	{			
		pos.display.add('1','article One',2.50);
		pos.display.add('2','article Two',2.50);
		pos.display.add('2','article Three',2.50);
		pos.display.add('1','article Four',2.50);
		pos.display.add('1','article Five',2.50);
		alert(pos.display.lines.length);
		alert(pos.display.lines[2].article);
	}
	</script>
</head>
<body>
<input type="submit" name="test" id="test" value="test" onclick="test()" />
</body>
</html>

Open in new window

LVL 2
ricosuaveAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HonorGodSoftware EngineerCommented:
One thing that I noticed is that you have used "reserved" or "keyword" identifiers as attributed names in your object.  (e.g., "clear", and "select").  This is strongly discouraged because different browsers can act differently when this is done.  For example, one browser may consider the code invalid, and "disavow any knowledge of the code" (i.e., ignore it completely).  Another browser may work "just fine"

looking further.
0
ricosuaveAuthor Commented:
Hi HonorGod,

I know these are dangerous terms, I have looked them up, however in a list of reserved words for javascript and they appear not to be reserved words: http://javascript.about.com/library/blreserved.htm
But then again, maybe this list is out of date.
0
HonorGodSoftware EngineerCommented:
What is going on is that you have one, and only one global object named line.
Each element of your array is pointed to this single global object instance by this code:

this.lines[ this.count ] = line;

What you need to do is create a new "line" object for this structure.

One moment please...
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

HonorGodSoftware EngineerCommented:
For example, something like this perhaps...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html>
<head>
<title></title>
<style type="text/css">
  @import url(/~css/main.css);
</style>
<script type='text/javascript'>
  function line( amount, article, price ) {
    this.quan  = amount;
    this.text  = article;
    this.cost  = price;
    this.edit  = function(){ alert( 'edit line'   ) },
    this.klear = function(){ alert( 'clear line'  ) },
    this.pick  = function(){ alert( 'select line' ) }
  }
  
  var pos = {
    display    : {
      count    : 0,
      selected : null,
      lines    : [],
      add      : function( amount, article, price ) {
                   this.lines[ this.count++ ] = new line( amount, article, price );
                 }
    }
  };
          
  function field( id, msg ) {
    var obj = document.getElementById( id );
    if ( !obj ) {
      alert( msg );
    }
    return obj;
  }
  
  function test() {                       
    pos.display.add( '1', 'article One'  , 2.50 );
    pos.display.add( '2', 'article Two'  , 2.50 );
    pos.display.add( '2', 'article Three', 2.50 );
    pos.display.add( '1', 'article Four' , 2.50 );
    pos.display.add( '1', 'article Five' , 2.50 );
    var msg = '';
    var len = pos.display.lines.length;
    msg += 'pos.display.lines.length = ' + len;
    for ( var i = 0; i < len; i++ ) {
      msg += '<br>lines[ ' + i + ' ].text = "' + pos.display.lines[ i ].text + '"';
    }
    field( 'debug' ).innerHTML = msg;
  }
</script>
</head>
<body>
<input type="submit" name="test" id="test" value="test" onclick="test()" />
<div id='debug'></div>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ricosuaveAuthor Commented:
Thanks, I'll go and check this out. Will get back to you.
0
HonorGodSoftware EngineerCommented:
If you need information about object, and their creation, you might want to take a look at:

http://www.javascriptkit.com/javatutors/object.shtml
0
ricosuaveAuthor Commented:
HonorGod, this works like a charm, every line needs to be a new object, just like you said. Thanks a lot !
0
Michel PlungjanIT ExpertCommented:
Good find. I KNEW it was something with new ;)
0
ricosuaveAuthor Commented:
Hi Michel,
I've read IRT.org since I started webdeveloping like 10 years ago or so. It was my primary source of js information vack then, and I remember your name from that site, I figure this must be something you knew, right?
(Or is javascript still developing so fast that a veteran like you learns new tricks from experst exchange now and then?)
:)
0
HonorGodSoftware EngineerCommented:
Michel - thanks for the compliment. :-)

ricosuave : Thanks for the Grade, the points, and as bol would say, the interesting question.
0
Michel PlungjanIT ExpertCommented:
ricosuave: Of course I can learn - I personally have very little hands on experience with the above way of notating JS.
I see it in all the libraries (prototype, extjs)  I do need to get to grips with it and JSON.
OO is not my native approach so when I played with your script I had a nagging feeling that a "new" was needed somewhere, but I could not put my finger on where.
I was looking at
this.lines[this.lines.length] = line( amount, article, price );

to eliminate the count - but when I saw
... = new line( amount, article, price );
the dime dropped...
PS: It is very sad that IRT.org is readonly since a few years. However keep an eye on my personal site in the time to come...
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.