JavaScript - Ayuda con método en generador de objetos

 
Vista:
sin imagen de perfil

Ayuda con método en generador de objetos

Publicado por Juaki (3 intervenciones) el 23/09/2014 22:44:26
Hola!
Me estoy iniciando en la programación web. Actualmente Estoy con javaScript. Me peguntaba si me podrías ayudar en este pequeño programa.
Lo que quiero conseguir es que me escriba en la DOM a qué hora es el próximo tren.
Para ello, creo 3 objetos (trenes) con un generador el cual tiene un método al que llamo posteriormente para obtener cual es el próximo tren en función de la hora en que estamos.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<!doctype html>
<html lang="en">
<head>
	<title>Train</title>
	<meta charset="utf-8">
	<style>
			table, td {
			    border: 1px solid black;
			    border-collapse: collapse;
			}
	</style>
	<script>
 
	//Generador de Objetos. Creo los trenes objetos con esta funcion
	function Train(title, traintimes) {
		this.title = title;
		this.traintimes = traintimes;
		this.getNextTrain = function() {
			var now = new Date().getTime(); //Obtengo el tiempo actual en ms 
			for (var i = 0; i < this.traintimes.length; i++) {
				var traintime = getTimeFromString(this.traintimes[i]); //Por cada horario de tren, ontengo el tienpo en ms para comparar
				if ((traintime - now) > 0) {
					if (this.title === "Economy Class"){
 
						var tren = "Next  " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("economy");
						currentTren.innerHTML = tren;
						return true;
					}else if (this.title === "Bussines Class"){
 
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("bussines");
						currentTren.innerHTML = tren;
						return true;
					}else{
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("firstClass");
						currentTren.innerHTML = tren;
						return true;
					}
				}
			}
			return null;
		};
	}
 
	/*
	código que toma una cadena con el formato como 01 am o 3:00 pm y la convierte a un tiempo en millisegundos
	*/
 
	function getTimeFromString(str) {
		var theTime = new Date();
		var time = str.match(/(\d+)(?::(\d\d))?\s*(p?)/);
		theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
		theTime.setMinutes( parseInt(time[2]) || 0 );
		return theTime.getTime();
	}
 
	//Train 1
	var economyTrain = new Train ("Economy Class",
						   ["1:00pm", "5:00pm", "9:00pm", "11:00pm"]);
 
	//Train 2
	var bussinesTrain = new Train ("Bussines Class",
						   ["3:00pm", "10:00pm", "11:00pm"]);
 
	//Train 3
	var firstClassTrain = new Train ("First Class",
						   ["5:00pm", "9:00pm"]);
 
 
 
	var train1 = document.getElementById("econ");
	train1.onclick = economyTrain.getNextTrain();
 
 
	var train2 = document.getElementById("buss");
	train2.onclick = bussinesTrain.getNextTrain();
 
	var train3 = document.getElementById("firs");
	train3.onclick = firstClassTrain.getNextTrain();
 
 
 
	</script>
 
 
</head>
<body>
 
	<table>
		<tr>
			<td><h3>Economy Trains</h3></td>
			<td><p> Time tables: 1:00pm  5:00pm  9:00pm  11:00pm</p></td>
		</tr>
 
		<tr>
			<td><h3>BussinesTrain</h3></td>
			<td><p> Time tables: 3:00pm  10:00pm  11:00pm</p></td>
		</tr>
 
		<tr>
			<td><h3>FirstClassTrain</h3></td>
			<td><p> Time tables: 5:00pm  9:00pm</p></td>
		</tr>
	</table>
 
	<form>
		<input type="button" value="Get next Economy train" id="econ">
		<input type="button" value="Get next Bussines trains" id="buss">
		<input type="button" value="Get next First Class trains" id="firs">
	</form>
 
        <div id="economy"></div>
	<div id="bussines"></div>
        <div id="firstClass"></div>
</body>
</html>


Este código me da el error: "Uncaught TypeError: Cannot set property 'innerHTML' of null"



Pense que el error era que aún no se había cargado la página y añadí la función onload a los botones. Pero al compilar no obtengo ninguna salida.

1
2
3
4
5
6
7
8
9
10
11
12
13
function init (){
	var train1 = document.getElementById("econ");
	train1.onclick = economyTrain.getNextTrain();
 
 
	var train2 = document.getElementById("buss");
	train2.onclick = bussinesTrain.getNextTrain();
 
	var train3 = document.getElementById("firs");
	train3.onclick = firstClassTrain.getNextTrain();
 
    }
    window.onlad = init;

Me podeís ayudar?? Levo atascado días y no encuentro el fallo?? Q hago mal?

Muchísimas gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Ayuda con método en generador de objetos

Publicado por xve (2100 intervenciones) el 24/09/2014 07:50:57
Hola Juaki, tu problema, es que cuando estas haciendo referencia al id "economy", este todavía no se ha creado, ya que ejecutas el código de javascript antes de que exista el código html...

Para ello, puedes incluir las llamadas a la función Train dentro del onload... algo así:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
window.onload=function(){
	//Train 1
	var economyTrain = new Train ("Economy Class",
						["1:00pm", "5:00pm", "9:00pm", "11:00pm"]);
 
	//Train 2
	var bussinesTrain = new Train ("Bussines Class",
						["3:00pm", "10:00pm", "11:00pm"]);
 
	//Train 3
	var firstClassTrain = new Train ("First Class",
						["5:00pm", "9:00pm"]);
 
	var train1 = document.getElementById("econ");
	train1.onclick = economyTrain.getNextTrain();
 
 
	var train2 = document.getElementById("buss");
	train2.onclick = bussinesTrain.getNextTrain();
 
	var train3 = document.getElementById("firs");
	train3.onclick = firstClassTrain.getNextTrain();
}

Coméntanos, ok?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Ayuda con método en generador de objetos

Publicado por Juaki (3 intervenciones) el 24/09/2014 11:35:47
Muchísimas gracias por la ayuda. Cierto, aún no estaba creado.

Por fin el código compila correctamente y me da los resultados esperados. Lo único es que al cargar la página ya me muestra los resultados insertados en el DOM y lo que intento es que los muestre cuando presione el botón correspondiente.

De alguna manera parece ser que me accede a la llamada a la función y ejecuta el código. Lo que no entiendo es porqué, ya que dicha llamada debe hacerse cuando hago click en el botón. En cambio, no hago ningún click y el código se ejecuta al cargar la página....

Voy a darle mas vueltas a ver si consigo descifrar algo..

Muchísimas gracias de nuevo!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<!doctype html>
<html lang="en">
<head>
	<title>Train</title>
	<meta charset="utf-8">
	<style>
			table, td {
			    border: 1px solid black;
			    border-collapse: collapse;
			}
	</style>
 
	<script>
 
 
 
	//Generador de Objetos. Creo los trenes objetos con esta funcion
	function Train(title, traintimes) {
		this.title = title;
		this.traintimes = traintimes;
		this.getNextTrain = function() {
			var now = new Date().getTime(); //Obtengo el tiempo actual en ms 
			for (var i = 0; i < this.traintimes.length; i++) {
				var traintime = getTimeFromString(this.traintimes[i]); //Por cada horario de tren, ontengo el tienpo en ms para comparar
				if ((traintime - now) > 0) {
					if (this.title === "Economy Class"){
 
						var tren = "Next  " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("economy");
						currentTren.innerHTML = tren;
						return true;
					}else if (this.title === "Bussines Class"){
 
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("bussines");
						currentTren.innerHTML = tren;
						return true;
					}else{
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("firstClass");
						currentTren.innerHTML = tren;
						return true;
					}
				}
			}
			return null;
		};
	}
 
	/*
	código que toma una cadena con el formato como 01 am o 3:00 pm y la convierte a un tiempo en millisegundos
	*/
 
	function getTimeFromString(str) {
		var theTime = new Date();
		var time = str.match(/(\d+)(?::(\d\d))?\s*(p?)/);
		theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
		theTime.setMinutes( parseInt(time[2]) || 0 );
		return theTime.getTime();
	}
 
 
 
	window.onload=function(){
		//Train 1
		var economyTrain = new Train ("Economy Class",
							["1:00pm", "5:00pm", "9:00pm", "11:00pm"]);
 
		//Train 2
		var bussinesTrain = new Train ("Bussines Class",
							["3:00pm", "10:00pm", "11:00pm"]);
 
		//Train 3
		var firstClassTrain = new Train ("First Class",
							["5:00pm", "9:00pm"]);
 
		var train1 = document.getElementById("econ");
		train1.onclick = economyTrain.getNextTrain();
 
 
		var train2 = document.getElementById("buss");
		train2.onclick = bussinesTrain.getNextTrain();
 
		var train3 = document.getElementById("firs");
		train3.onclick = firstClassTrain.getNextTrain();
	}
 
	</script>
 
 
</head>
<body>
 
	<table>
		<tr>
			<td><h3>Economy Trains</h3></td>
			<td><p> Time tables: 1:00pm  5:00pm  9:00pm  11:00pm</p></td>
		</tr>
 
		<tr>
			<td><h3>BussinesTrain</h3></td>
			<td><p> Time tables: 3:00pm  10:00pm  11:00pm</p></td>
		</tr>
 
		<tr>
			<td><h3>FirstClassTrain</h3></td>
			<td><p> Time tables: 5:00pm  9:00pm</p></td>
		</tr>
	</table>
 
	<form>
		<input type="button" value="Get next Economy train" id="econ">
		<input type="button" value="Get next Bussines trains" id="buss">
		<input type="button" value="Get next First Class trains" id="firs">
	</form>
 
 
	<div id="economy"></div>
 
	<div id="bussines"></div>
 
	<div id="firstClass"></div>
 
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Ayuda con método en generador de objetos

Publicado por xve (2100 intervenciones) el 24/09/2014 21:46:30
Si claro, tienes las llamadas en el onload... por lo que en el momento que se carga la página, hace las llamadas. Si quieres que lo haga desde algun botón, puedes utilizar el onlclik

No se si sabes bien como hacerlo...
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Ayuda con método en generador de objetos

Publicado por Juaki (3 intervenciones) el 25/09/2014 11:08:45
Es decir, que al estar el onclick dentro de la funcíon onload, se ejecutaba???

Ok, pues eso no lo sabía yo, pensé que el onclick era únicamente si el usuario hace "click". Error de concepto mío.

He probado a utilizar addEventListener.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
window.onload=function(){
 
		//Train 1
		var economyTrain = new Train ("Economy Class",
							["10:00am", "5:00pm", "9:00pm", "11:00pm"]);
 
		//Train 2
		var bussinesTrain = new Train ("Bussines Class",
							["3:00pm", "10:00pm", "11:00pm"]);
 
		//Train 3
		var firstClassTrain = new Train ("First Class",
							["5:00pm", "9:00pm"]);
 
 
		document.getElementById("econ").addEventListener("click", economyTrain.getNextTrain);
		document.getElementById("buss").addEventListener("click", bussinesTrain.getNextTrain);
		document.getElementById("firs").addEventListener("click", firstClassTrain.getNextTrain);
 
 
	}
Llamando al método "getNextTrain" que está dentro del generador:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function Train(title, traintimes) {
		this.title = title;
		this.traintimes = traintimes;
		this.getNextTrain = function() {
			var now = new Date().getTime(); //Obtengo el tiempo actual en ms 
			for (var i = 0; i < this.traintimes.length; i++) {
				var traintime = getTimeFromString(this.traintimes[i]); //Por cada horario de tren, ontengo el tienpo en ms para comparar
				if ((traintime - now) > 0) {
					if (this.title === "Economy Class"){
 
						var tren = "Next  " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("economy");
						currentTren.innerHTML = tren;
						return true;
					}else if (this.title === "Bussines Class"){
 
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("bussines");
						currentTren.innerHTML = tren;
						return true;
					}else{
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("firstClass");
						currentTren.innerHTML = tren;
						return true;
					}
				}
			}
			return null;
		};
	}
Al principio me daba el error: "Uncaught TypeError: Cannot read property 'length' of undefined "


Esto no lo entiendo mucho, porque al llamar al método con "economyTrain.getNextTrain", "bussinesTrain.getNextTrain" y "firstClassTrain.getNextTrain" se supone que los objetos Trenes con sus propiedades ya están creados anteriormente cuando hago
1
2
3
var economyTrain = new Train ("Economy Class", ["10:00am", "5:00pm", "9:00pm", "11:00pm"]);
	var bussinesTrain = new Train ("Bussines Class", ["3:00pm", "10:00pm", "11:00pm"]);
	var firstClassTrain = new Train ("First Class", ["5:00pm", "9:00pm"]);
Es decir, creía que al llamarlos en:
1
2
3
document.getElementById("econ").addEventListener("click", economyTrain.getNextTrain);
	document.getElementById("buss").addEventListener("click", bussinesTrain.getNextTrain);
	document.getElementById("firs").addEventListener("click", firstClassTrain.getNextTrain);

ya estaban totalmente creados.

----------------------

Pues como me daba este error, he introducido (por probar)
1
2
this.title = title;
	this.traintimes = traintimes;
dentro del método y el programa me hace ya por fin todo lo que yo quiero. Así es como me ha quedado y me funciona:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!doctype html>
<html lang="en">
<head>
	<title>Train Foro 1</title>
	<meta charset="utf-8">
	<style>
			table, td {
			    border: 1px solid black;
			    border-collapse: collapse;
			}
	</style>
 
	<script>
 
	//Generador de Objetos. Creo los trenes objetos con esta funcion
	function Train(title, traintimes) {
		 this.getNextTrain = function() {
			this.title = title;
			this.traintimes = traintimes;
			var now = new Date().getTime(); //Obtengo el tiempo actual en ms 
			for (var i = 0; i < this.traintimes.length; i++) {
				var traintime = getTimeFromString(this.traintimes[i]); //Por cada horario de tren, obtengo el tiempo en ms para comparar
				if ((traintime - now) > 0) {
					if (this.title === "Economy Class"){
 
						var tren = "Next  " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("economy");
						currentTren.innerHTML = tren;
						return true;
					}else if (this.title === "Bussines Class"){
 
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("bussines");
						currentTren.innerHTML = tren;
						return true;
					}else{
						var tren = "Next " + this.title + " train is at " + this.traintimes[i];
						var currentTren = document.getElementById ("firstClass");
						currentTren.innerHTML = tren;
						return true;
					}
				}
			}
			return null;
		};
	}
 
	/*
	código que toma una cadena con el formato como 01 am o 3:00 pm y la convierte a un tiempo en millisegundos
	*/
 
	function getTimeFromString(str) {
		var theTime = new Date();
		var time = str.match(/(\d+)(?::(\d\d))?\s*(p?)/);
		theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
		theTime.setMinutes( parseInt(time[2]) || 0 );
		return theTime.getTime();
	}
 
	window.onload=function(){
 
		//Train 1
		var economyTrain = new Train ("Economy Class",
							["10:00am", "5:00pm", "9:00pm", "11:00pm"]);
 
		//Train 2
		var bussinesTrain = new Train ("Bussines Class",
							["3:00pm", "10:00pm", "11:00pm"]);
 
		//Train 3
		var firstClassTrain = new Train ("First Class",
							["5:00pm", "9:00pm"]);
 
		document.getElementById("econ").addEventListener("click", economyTrain.getNextTrain);
		document.getElementById("buss").addEventListener("click", bussinesTrain.getNextTrain);
		document.getElementById("firs").addEventListener("click", firstClassTrain.getNextTrain);
	}
 
	</script>
 
</head>
<body>
 
	<table>
		<tr>
			<td><h3>Economy Trains</h3></td>
			<td><p> Time tables: 10:00am  5:00pm  9:00pm  11:00pm</p></td>
		</tr>
		<tr>
			<td><h3>BussinesTrain</h3></td>
			<td><p> Time tables: 3:00pm  10:00pm  11:00pm</p></td>
		</tr>
		<tr>
			<td><h3>FirstClassTrain</h3></td>
			<td><p> Time tables: 5:00pm  9:00pm</p></td>
		</tr>
	</table>
 
	<form>
		<input type="button" value="Get next Economy train" id="econ">
		<input type="button" value="Get next Bussines trains" id="buss">
		<input type="button" value="Get next First Class trains" id="firs">
	</form>
 
	<div id="economy"></div>
	<div id="bussines"></div>
	<div id="firstClass"></div>
 
</body>
</html>

Supongo que no entiendo bien la teoría sobre los objetos. Me toca estudiarla más.

No sabes como te agradezco tu ayuda. Me has ayudado a comprender un poco más cómo funciona javaScript.
Muchísimas gracias!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar