javascript, aplicaciones y framewors tutor: ing. juan e. talavera horn 2010

Post on 02-Apr-2015

111 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Javascript, aplicaciones y framewors

Tutor: Ing. Juan E. Talavera Horn

2010

Contenido

JavaScript Object Notation – JSON Orientación a objetos - Sintaxis Name spaces - Concepto AJAX – Concepto y ejemplos Revisión de algunos frameworks

JavaScript Object Notation - JSON

var persona = { nombre: “Juan”, apellido: “Pérez”,

nacionalidad: “Paraguaya” };

JavaScript Object Notation - JSONJSON (JavaScript Object Notation) is a lightweight data-interchange format. (http://www.json.org)

Basado en un subconjunto del lenguaje JavaScript

Es un formato de texto independiente del lenguaje pero con construcciones similares a lenguajes de la familia C.

Construido sobre 2 estructuras básicas:

1. Una colección de pares nombre/valor (record, struct, hash, etc.)2. Una lista ordenada de valores (array, list, sequence, etc.)

JavaScript Object Notation - JSON

JavaScript Object Notation - JSON

var numeros = [1,2,3,4,5,6];

var nombres = [“Maria”,”Helena”,”Julio”];

JavaScript Object Notation - JSON

var menu = { id: "file", value: "File", popup: { menuitem: [ {value: "New", onclick: "CreateNewDoc()"},

{value: "Open", onclick: "OpenDoc()"}, {value: "Close", onclick: "CloseDoc()"} ]

} }

Orientación a Objetos - OO- Creación de objeto con new Object()

person = new Object() ;person.name = "Tim Scarfe" ;person.height = "6Ft" ;person.run = function() { this.state = "running“; this.speed = "4ms^-1" };

-Creación de objeto con notación literal (literal notation)

timObject = {property1 : "Hello",property2 : “Una descripcion cualquiera",property3 : ["mmm", 2, 3, 6, “xyz"],method1 : function(){

alert(“Llamando method 1”)}

};

timObject.method1();alert(timObject.property3[2]) // muestra “3”

Orientación a Objetos - OO

-Constructor Method

function person(name) { this.name = name; this.talk = function() { alert( this.name + " dice holaa!" ) } }

person1 = new person(“Maria")person1.talk() //Maria dice holaa! person2 = new person(“Julia") person2.talk() //Julia dice holaa!

Orientación a Objetos - OO

-Prototyping

Mecanismo que permite agregar un método a un objeto después que este haya sido definido, e inmediatamente todas las instancias de la misma clase comparten dicho método.

person.prototype.changeName = function(name) {this.name = name;

}

person1 = new person(“Mario")person1.changeName("Bill")person1.talk() //alerts "Bill dice holaa!"

Obs: Se pueden agregar métodos a cualquier objeto (incluso los built-in como Array, Date, etc) que se inicialicen con new(). To prototype an object.

Orientación a Objetos - OO- Herencia usando Constructor Method

function superClass() { this.supertest = superTest; //attach method superTest }

function subClass() { this.inheritFrom = superClass; this.inheritFrom(); this.subtest = subTest; //attach method subTest }

function superTest() { return "superTest"; }

function subTest() { return "subTest"; }

var newClass = new subClass(); alert(newClass.subtest()); // muestra "subTest" alert(newClass.supertest()); // muestra "superTest"

AJAX (Asynchronous JavaScript + XML)

Metodología que permite, una vez cargada y procesada una página, comunicarse mediante eventos y rutinas con el servidor buscando en background los datos.

Con los datos traídos en background se pueden actualizar porciones específicas de la página, sin recargar todo el contenido del documento en el navegador.

AJAX - Ejemplo de uso (API de ejemplo)<html>

<script>

function traerNombres() {

var callback = {onSuccess: function (resp) {

$(‘nombres’).innerHTML = resp.responseText;

},

onFailure: function(error) {

window.alert(“Ocurrió el error”: error.message);

}

};

var request = new Ajax.Request(“/traerDatosPersona.php”,

{ cedula: $(‘cedula’).value },

callback);

}

</script>

<form>

Cedula: <input type=“text” name=“cedula” id=“cedula” onblur=“traerNombres()”>

Nombre: <div id=“nombres”>[Ingrese una cédula …]</div>

</form>

</html>

Frameworks JavaScript

Prototype (www.prototypejs.org) Mootools (www.mootools.net) JQuery (www.jquery.com) YUI: "The Yahoo! User Interface Library" (http://

developer.yahoo.com/yui/) Dojo (http://www.dojotoolkit.org/ ) GWT Google Web Toolkit (

http://code.google.com/webtoolkit/) ExtJS (http://www.extjs.com)

Ajax con Prototype

new Ajax.Request('/some_url', {method:'get', parameters: {company: 'example', limit: 12},

onSuccess: function(transport){ var response = transport.responseText;

alert("Success! \n\n" + response); },

onFailure: function(){ alert(‘Hubo algun error...')

} });

Actualización Parcial con AJAX

Asignar Id a bloque a actualizar Programar evento con invocación AJAX para

actualización En callback asignar al innerHTML nuevo

contenido del bloque a actualizar En el servidor, programar lógica para

proveer contenido en función a los parámetros del AJAX Request.

Actualización parcial con Prototype…

<h2>Lista de productos</h2> <div id="products">(Obteniendo lista de productos ...)</div>

<script>…new Ajax.Updater('products', '/some_url', { method: 'get' });…</script>

Actualización parcial periodica con Prototype

new Ajax.PeriodicalUpdater('products', '/some_url', { method: 'get', frequency: 30 });

AJAX Request con YUI

var callback = {

success: function(o) {/*success handler code*/}, failure: function(o) {/*failure handler code*/}, argument: [argument1, argument2, argument3]

}

var cObj = YAHOO.util.Connect.asyncRequest('POST',

'http://www.yahoo.com', callback

);

Namespaces – Espacio de nombres

var NtroEspacio = function() { var private_var; function private_method() { // do stuff here }

return { method_1 : function() { // do stuff here }, method_2 : function() { // do stuff here }

}; }();

Namespaces – Espacio de nombresvar NtroEspacio = function(){

// private functions and propertiesvar _private = {

metodoPrivado1 : function(method, url, data) {

return “Mensaje 2”; }

};var _public = {

metodoPublico1 : function(url) {

return “Mensaje 1”; },metodoPublico2 : function(form) {

return _private.metodoPrivado1(); }

};

return _public;}();

Gracias …

top related