ws_extjs

Post on 01-Dec-2015

35 views 0 download

Tags:

Transcript of ws_extjs

Taller de introducción

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Framework javascript para construir aplicaciones RIA.• Crecimiento y actualización constante.• Crossbrowser.• Más de 20 widgets modernos y ricos en funcionalidad.• Claro y definido modelo de componentes.• Modelo orientado a la extensibilidad.• API completa y comunidad activa.

Características generales:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JSCaracterísticas generales:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Ext Designer:• Aplicación de escritorio

que ayuda a crear interfaces de manera rápida en un ambiente fácil de usar y en modo drag & drop.

Herramientas de apoyo:

• Permite diseñar y ensamblar rápidamente componentes.• WYSING• Provee de conectividad a datos permitiendo poblar las UIs en

diseño.

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Independencia del backend.

• Intercambio de datos vía JSON o XML.

• RESTful ready.

Integración con plataformas:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Una vez descargado el paquete desde http://www.sencha.com se debe descomprimir el contenido e incluir las librerías base para permitir instanciar el objeto Ext en una página web.

• Los archivos mínimos requeridos son:• [directorio ext]/resources/css/ext-all.css• [directorio ext]/adapter/ext/ext-base.js• [directorio ext]/ext-all.js

Instalación:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JSVista al descomprimir el paquete:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Los archivos ext-all.js representan la totalidad del framework en un solo archivo.

• Diferencias entre:• ext-all.js• ext-all-debug.js• ext-all-debug-w-comments.js

Y porqué tantos ext-all ?:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Para inicializar Ext se debe invocar el siguiente código en un tag script o en un archivo js incluído en el html.

Ext.onReady(function(){//ya puedo invocar a Ext!!});

Inicialización simple:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 1 !!

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Ext.util.Observable• Ext.Component

• Ext.Panel• Ext.Window• …

Introducción al modelo de componentes:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Representa la entrega de configuración para la instanciación de objetos en ExtJS.

• La figura estructural es:

{ [propiedad] : [valor|función]}

new Ext.Button({    renderTo: Ext.getBody(),    text : 'Abrir ventana'});

El objeto config:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Panel es un container que tiene una funcionalidad específica: permitir alojar bloques de otros componentes para diseñar aplicaciones orientadas a interfaces de usuario.

• Un Panel por virtud de la herencia de Ext.Container, capaz de ser configurado con un layout y contener componentes hijos.

• Pueden contener “top” y “bottom” toolbars.• Y muchas configuraciones adicionales.

new Ext.Panel({    objeto config});

Componente Ext.Panel:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Layouts: column, form, panel, fit, table, card, etc.• Toolbars: barras alojadoras de componentes.

• Top se alojan en la zona superior del panel• Bottom se alojan en la zona inferior del panel• Objetos default, separators, fills

• Una característica es que se renderea a un contenedor o a un elemento HTML, por medio del método render()

Componente Ext.Panel:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Son inherentes al objeto Panel, pero su uso es masivo en esta clase de componentes.

• Son los handlers una de sus características más importantes, ya que definen comportamiento.

new Ext.Button({    renderTo: Ext.getBody(),    text : 'Abrir ventana'});

Componente Ext.Button:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Su implementación en un toolbar existente en un Panel, puede darse de la siguiente forma:

new Ext.Panel({ //toolbar

    tbar : [{ //declaración del botón text: ‘Nombre del botón’,

//handlerhandler: function(){

alert(‘hola’);}

}]});

Componente Ext.Button:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Componente de alerta y decisión.

Ext.Msg.show({ title:'Save Changes?', msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?', buttons: Ext.Msg.YESNOCANCEL, fn: processResult, icon: Ext.MessageBox.QUESTION

});

Componente Ext.MessageBox:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Es un Panel que flota…• En vez de render(), tiene show()

var window = Ext.Window({ title:‘Window !', buttons: [{

text: ‘Cerrar’}]

});window.show();

Componente Ext.Window:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Son formas similares de instancias componentes, pero existe una diferencia funcional que tiene impacto a nivel de performance.

• El operador new() instancia un objeto de manera instantánea. • El modo xtype, instancia el objeto solamente cuando el

componente padre es instanciado y renderizado al browser.

var window = new Ext.Window({ title:‘Window !', buttons: [{

xtype: ‘button’,text: ‘Cerrar’

}] });window.show();

Diferencias entre xtypes y new():

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• La gran mayoría de los componentes, implementan la interface Observable, por lo tanto, todos ellos disparan eventos. Eventos de ejemplo pueden ser: click, select, load, etc.

• Las funciones que manejan esos eventos, se llaman listeners.• Existen dos formas de capturar los eventos por medio de los

listeners:

1. En la misma declaración del componente.

2. Mediante el listener “on”.

Events y listeners:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

1. En la misma declaración del componente.new Ext.Button({

…listeners: {

click : function(){alert(‘Cliqueaste el botón’);

}}

});

Events y listeners: invocaciones.

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

2. Mediante el listener “on”.Var b = new Ext.Button({

…});

b.on(‘click’, function(){alert(‘cliqueaste el botón’);

});

Events y listeners: invocaciones.

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 2 !!

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Es el contenedor estándar de formularios y sus elementos.• Configurado por default con layout “form”.• Extiende de BasicForm• Posee métodos integrados de validación, carga y envío de datos.

new Ext.form.FormPanel({    objeto config});

Componente Ext.form.FormPanel:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Es posible todos los elementos del paquete form, entre los que destacan:

1. Textfields

2. Datefields

3. Textareas

4. Spinners

5. Combos

6. Composite fields

7. Etc.

Componente Ext.form.FormPanel:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Los métodos más utilizados son:

1. getForm() Recupera una instancia del BasicForm para la utilización de isValid(), submit() y load(), entre otros.

2. isValid() Valida el formulario, según las contraints definidas para cada elemento contenido.

3. submit({config}) Hace el submit del formulario. Puede hacer un submit tradicional o a un backend vía REST o similar.

4. load({}) Carga un formulario desde un backend REST o similar.

5. loadRecord(Record) Carga un formulario por medio de un Record.

Componente Ext.form.FormPanel:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 3 !!

Break?

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Hasta ahora hemos trabajado los componentes Ext directo desde archivos JS o invocándolos directamente desde el HTML.

• El problema es como encapsulamos nuestra implementación en una componente que sea reutilizable.

• Ext.extend permite una forma fácil de crear clases en Javascript que extienden de componentes Ext.

• Algunos conceptos previos:• Namespace• Scope• UI y Behavior

Ext.extend y la reutilización:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Namespace: por medio del singleton Ext.ns(‘[nombre del namespace]’); permite establecer un espacio de nombres común para componentes OOP.

• Scope: IMPORTANTE! En javascript, el contexto existe en la variable this. Este contexto no es “pasado” de manera automática en la medida que se anidan objetos config. Ext provee de una forma de entrega del scope a componentes anidados, pero es manual.

Ext.extend y la reutilización:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• UI y Behavior: en EXE, al crear componentes mediante Ext.extend() y que consiste en la separación, en 2 archivos javascript, del código implementado.• Un archivo [tipoComponenteNombreComponente].ui.js• Un archivo [tipoComponenteNombreComponente].behavior.js

• En el UI: se extiende del componente Ext genérico y se programa todo el armado de componentes a nivel gráfico, sin funcionalidad.

• En el behavior: se extiende del componente UI, se declaran los eventos y se implementan sus handlers con lógica.

Ext.extend y la reutilización:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 4 !!

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Entendiendo JSON:• JSON, acrónimo de JavaScript Object Notation, es un formato

ligero para el intercambio de datos. JSON es un subconjunto de la notación literal de objetos de JavaScript que no requiere el uso de XML. (Wikipedia )

• Ejemplo de JSON: (similitudes?){

nombre : ‘Pablo’apellido : ‘Voss’datos : {

sexo: ‘?’,edad: 20

}}

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Entendiendo JSON:• Todas las peticiones AJAX en Ext, requieren de un JSON

mínimo esperado, el cual debe retornar (con algunas variaciones mínimas)

{success : true // o false, siempre debe venir// otros datosdatos : {

sexo: ‘?’,edad: 20

}}

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Ext.Ajax:• Request global de AJAX que provee una manera simple de

realizar ajax requests con una gran flexibilidad.

Ext.Ajax.request({url: 'algo.php',method: 'POST',success: function(response, opts){

console.log(response);},failure: function(response, opts){

console.log(response);},params: { parametro1: 'valor1' }

});

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Ext.util.JSON:• Singleton utilitario que permite codificar y decodificar

elementos desde y hacia JSON.

Ext.decode(response); //convierte a objeto el JSON retornado desde el backend

var array = new Array(array(‘hola’), array(1));Console.log(Ext.encode(array));

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

form.submit:• Método que permite enviar a un backend REST o similar, los

elementos que se contienen en un formulario.

miForm.getForm().submit({ url : ‘url destino‘, method : ‘POST‘, //o GET o PUT o DELETE si es RESTful success : function(){} //para manejar la respuesta exitosa failure : function(){} //para manejar la respuesta fallida});

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

form.load:• Método que permite invocar un procedimiento de backend

como un servicio REST, el cual puede retornar un JSON que permita poblar automáticamente el formulario.

miForm.getForm().load({ url : ‘url destino‘, method : ‘POST‘, //o GET o PUT o DELETE si es RESTful success : function(){} //para manejar la respuesta exitosa failure : function(){} //para manejar la respuesta fallida});

Ext.Ajax y widgets de integración:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 5 y 6 !!

¿Break?

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Proxies: Representan la abstracción en la invocación de una llamada AJAX, en ExtJS. Existen los siguientes tipos:• HttpProxy• ScriptagProxy• MemoryProxy• DirectProxy

Proxies, Records y Stores:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Records: encapsula la definición de cierta información, en una estructura conocida para los elementos que utilizan Stores para mostrar la data.

Proxies, Records y Stores:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Stores: clase que encapsula un caché de cliente de objetos tipo Record, lo que representa el input para componentes como GridPanel, ComboBox y Dataview.

• Es posible recuperar y leer data, mediante una serie de métodos.• Tipos de store:

• ArrayStore• JsonStore• DirectStore• GroupingStore• XmlStore

Proxies, Records y Stores:

var myStore = new Ext.data.ArrayStore({ fields: [‘nombre', ‘email'], idIndex: 0});

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• ComboBox: lista desplegable que tiene soporte para autocomplete, carga remota, paginación y un montón de funcionalidades más.

Widgets que utilizan Stores:

var combo = new Ext.form.ComboBox({ typeAhead: true, triggerAction: 'all', mode: 'local', store: new Ext.data.ArrayStore({ id: 0, fields: [ 'myId', 'displayText' ], data: [[1, 'item1'], [2, 'item2']] }), valueField: 'myId', displayField: 'displayText'});

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 7 !!

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

• Grid: clase que representa la interfaz primaria de un componente basado en un control tipo grilla para representar data en formato tabular de filas y columnas.

Widgets que utilizan Stores:

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JSWidgets que utilizan Stores: Grid

var grid = new Ext.grid.GridPanel({ store: new Ext.data.Store({ autoDestroy: true, reader: reader, data: xg.dummyData }), colModel: new Ext.grid.ColumnModel({ defaults: { width: 120, sortable: true }, columns: [ {id: 'company', header: 'Company', width: 200, sortable: true, dataIndex: 'company'}, {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price'}, {header: 'Change', dataIndex: 'change'}, {header: '% Change', dataIndex: 'pctChange'}, // instead of specifying renderer: Ext.util.Format.dateRenderer('m/d/Y') use xtype { header: 'Last Updated', width: 135, dataIndex: 'lastChange', xtype: 'datecolumn', format: 'M d, Y' } ], }), sm: new Ext.grid.RowSelectionModel({singleSelect:true}), width: 600, height: 300, frame: true, title: ‘titulo', iconCls: 'icon-grid'});

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Ext JS

Taller 8 !!

Los Leones 382 Of. 102 · Providencia·Santiago-Chile ·Fono: (562) 335 30 37· Fax: (562) 234 44 76 ·Email: exe@exe.cl · Web: http://www.exe.cl

Fin