jump to navigation

Recursos para desarrollo Web junio 12, 2007

Posted by superpiwi in Ajax, Cursos, Eclipse, Java, Javascript, Programacion.
3 comments

Esta es una direccion con muchos recursos de programacion y de desarrollo web.
Muy muy interesante:

http://tutorialblog.org/

Coleccion impresionante de Data Grids en Ajax,dhtml y Javascript May 30, 2007

Posted by superpiwi in Ajax, Eclipse, Java, Javascript, Programacion.
add a comment

Con la cantidad de opciones que hay en esta pagina, ahora si que tengo dudas para elegir cual usar.

http://www.smashingmagazine.com/2007/05/30/tables-and-data-grids-with-ajax-dhtml-javascript/

Ajax ya May 9, 2007

Posted by superpiwi in Ajax, Cursos, Java, Javascript, Programacion.
add a comment

El objetivo de este tutorial es poder aprender Ajax viendo un concepto teórico, luego algunos ejercicios resueltos y otros por resolver.
Puede desarrollar los ejercicios en el sitio, probarlos, modificarlos y ver los resultados inmediatamente.

Ajax Ya

Documentacion de Prototype en PDF abril 24, 2007

Posted by superpiwi in Java, Javascript, Programacion.
add a comment

Prototype 1.5 API documentation

53 tecnicas basadas en CSS abril 24, 2007

Posted by superpiwi in Java, Javascript, Programacion.
1 comment so far

53 tecnicas basadas en CSS

Controlando el teclado con JavaScript abril 19, 2007

Posted by superpiwi in Java, Javascript, Programacion.
8 comments

En OpenJS me encuentro una libreria muy interesante. Nos permite mapear combinaciones de teclas para ejecutar las funciones javascript que queramos cuando se pulsen.Su utilizacion es muy sencilla. Ejemplo:


<HTML>
<HEAD>
</script><script src="shortcuts.js" type="text/javascript"></script>
<SCRIPT>
function init()
{
alert("iniciado");
shortcut("Ctrl+S",function()
{
alert("Has pulsado Control+S");
});
shortcut("Alt+E",function()
{
alert("Has pulsado Alt+E");
});
}
//addEvent(window,'load',init);
</SCRIPT>
</HEAD>
<BODY onload="init();">
Shorcuts...listos!!!...Pulsa "Control"+"S"
</BODY>
</HTML>

Con este ejemplo al pulsar Control+S o Alt+E se disparan las funciones. Podriamos mapear acciones de nuestra web con combinaciones de tecla.
Mas simple imposible.

Necesitas la siguiente libreria (actualmente en estado beta). Te la puedes descargar del sitio web, aunque aqui corto y pego su contenido
para que este accesible:

shortcuts.js


function shortcut(shortcut,callback,opt) {
//Provide a set of default options
var default_options = {
'type':'keydown',
'propagate':false,
'target':document
}
if(!opt) opt = default_options;
else {
for(var dfo in default_options) {
if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
}
}
var ele = opt.target
if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
var ths = this;
//The function to be called at keypress
var func = function(e) {
e = e || window.event;
//Find Which key is pressed
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code).toLowerCase();
var keys = shortcut.toLowerCase().split("+");
//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
var kp = 0;
//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
var shift_nums = {
"`":"~",
"1":"!",
"2":"@",
"3":"#",
"4":"$",
"5":"%",
"6":"^",
"7":"&",
"8":"*",
"9":"(",
"0":")",
"-":"_",
"=":"+",
";":":",
"'":"\"",
",":"<",
".":">",
"/":"?",
"\\":"|"
}
//Special Keys - and their codes
var special_keys = {
'esc':27,
'escape':27,
'tab':9,
'space':32,
'return':13,
'enter':13,
'backspace':8,
'scrolllock':145,
'scroll_lock':145,
'scroll':145,
'capslock':20,
'caps_lock':20,
'caps':20,
'numlock':144,
'num_lock':144,
'num':144,
'pause':19,
'break':19,
'insert':45,
'home':36,
'delete':46,
'end':35,
'pageup':33,
'page_up':33,
'pu':33,
'pagedown':34,
'page_down':34,
'pd':34,
'left':37,
'up':38,
'right':39,
'down':40,
'f1':112,
'f2':113,
'f3':114,
'f4':115,
'f5':116,
'f6':117,
'f7':118,
'f8':119,
'f9':120,
'f10':121,
'f11':122,
'f12':123
}
for(var i=0; k=keys[i],i<keys.length; i++) {
//Modifiers
if(k == 'ctrl' || k == 'control') {
if(e.ctrlKey) kp++;
} else if(k == 'shift') {
if(e.shiftKey) kp++;
} else if(k == 'alt') {
if(e.altKey) kp++;
} else if(k.length > 1) { //If it is a special key
if(special_keys[k] == code) kp++;
} else { //The special keys did not match
if(character == k) kp++;
else {
if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
character = shift_nums[character];
if(character == k) kp++;
}
}
}
}
if(kp == keys.length) {
callback(e);
if(!opt['propagate']) { //Stop the event
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works only in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
}
}
//Attach the function with the event
if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
else ele['on'+opt['type']] = func;
}

Serializame… marzo 7, 2007

Posted by superpiwi in Java, Javascript.
3 comments

He escrito una clase para serializar objetos java a un string XML y a cadenas JSON. (Para quien no lo sepa: ¿Que que es JSON?).
JSON (javascript object notation) es una forma de representar un objeto mediante una cadena de caracteres. Se suele emplear en JavaScript, aunque puedes usarlo donde mejor te venga. Yo lo suelo emplear con AJAX lo cuál me viene muy bien en muchas ocasiones en la que no quiero crear y parsear un XML (esto suele ser mas lento y tambien implica mas procesamiento).

Puedes encontrar informacion de JSON en http://www.json.org/

Bueno,… ¿Y para que nos puede servir convertir un objeto a una cadena de caracteres o a un XML String. Pues se me ocurren 2 buenas razones:

1) Para guardar el estado de un objeto . Es una manera de persistencia. Por ejemplo en una aplicacion de envio de paquetes, para la parte del seguimiento de un pedido, el pedido va pasando por diferentes estados, podriamos guardar el objeto en la base de datos, para posteriormente cuando cambie su estado, recuperarlo, actualizarlo y volver a guardarlo.

2) Para serializar un objeto, enviarlo por un socket a otra máquina y en el destino deserializarlo para poder acceder a sus métodos y propiedades o invocarlo remotamente.

No se, existen muchas mas utilidades. Seguro que se te ocurre alguna.

La clase se llama ObjectSerializer y es muy sencilla de utilizar. (La escribi hace tiempo, seguro que esto ha evolucionado, pero te puede ser util). Requiere de la siguiente libreria:

http://json-lib.sourceforge.net/

Aqui el código:


/**
* ObjectSerializer.java
*
* Clase de utilidad para codificar y decodificar un objeto a String empleando XML o una cadena JSON.
* Util por ejemplo para enviar el objeto a otra maquina e invocar sus metodos desde alli o para
* guardar su estado en la base de datos.
*
* @author jdelgado
* @version 0.0.1
* @since JDK 1.5
* @ide Eclipse 3.2 Callisto
* @revision 13 Julio 2006
*
* @note Para serializar/deserializar a JSON emplea la libreria json-lib.jar.
* @note Para serializar/deserializar a XML emplea las clases de Sun XMLEncoder y XMLDecoder.
*
* TODO: soporte para otros metodos (XStream, Castor, XMLBeans, etc...)
*/
package comun.util;
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.util.Vector;
public class ObjectSerializer
{
public static int XML_METHOD=0;
public static int JSON_METHOD=1;
/**
* Codifica un objeto a un String.
* @param o objeto para codificar.
* @param method metodo de la codificacion: XML_METHOD o JSON_METHOD.
* @return un string con el objeto codificado.
* @throws Exception Excepcion levantada en caso de error.
*/
public static String encode(Object o,int method) throws Exception
{
ByteArrayOutputStream bout = null;
if (method==ObjectSerializer.XML_METHOD)
{
// serializar a xml
bout = new ByteArrayOutputStream();
XMLEncoder e = new XMLEncoder(bout);
e.writeObject(o);
e.close();
String s = bout.toString();
return s;
}
else if(method==ObjectSerializer.JSON_METHOD)
{
// serializar a cadena json (javascript object notation)
JSONObject jsonObject = JSONObject.fromObject( o );
return jsonObject.toString();
}
else
{
throw new Exception("unknown method");
}
//return null;
}
//------------------------------
/**
* Codifica un objeto a un String.
* @param o objeto para codificar.
* @param method metodo de la codificacion: XML_METHOD o JSON_METHOD.
* @return un string con el objeto codificado.
* @throws Exception Excepcion levantada en caso de error.
*/
public static Object decode(String s,int method) throws Exception
{
ByteArrayInputStream bin = null;
if (method==ObjectSerializer.XML_METHOD)
{
// deserializar a xml
bin = new ByteArrayInputStream(s.getBytes());
XMLDecoder d = new XMLDecoder(bin);
Object result = d.readObject();
d.close();
return result;
}
else if(method==ObjectSerializer.JSON_METHOD)
{
// serializar a cadena json (javascript object notation)
JSONObject jsonObject = JSONObject.fromString(s);
return jsonObject;
}
else
{
throw new Exception("method unknown");
}
//return null;
}
//------------------------------
public static void main(String[] args) {
try
{
com.sqlmap.User usuario = new com.sqlmap.User();
usuario.setLogin("superpiwi");
usuario.setPassword("superpiwi");
usuario.setProfile("Usuario");
usuario.setSid("00001");
com.sqlmap.User usuario1 = new com.sqlmap.User();
usuario1.setLogin("jose");
usuario1.setPassword("jose");
usuario1.setProfile("Usuario Jose");
usuario1.setSid("00001-01");
com.sqlmap.User usuario2 = new com.sqlmap.User();
usuario2.setLogin("soledad");
usuario2.setPassword("soledad");
usuario2.setProfile("Usuario Soledad");
usuario2.setSid("00001-02");
usuario.addUser(usuario1);
usuario.addUser(usuario2);
// Codificarlos
String XML_STRING = ObjectSerializer.encode(usuario, ObjectSerializer.XML_METHOD);
System.out.println("Codificado como XML:\r\n\r\n"+XML_STRING);
String JSON_STRING = ObjectSerializer.encode(usuario, ObjectSerializer.JSON_METHOD);
System.out.println("Codificado como JSON:\r\n\r\n:"+JSON_STRING);
// Decodificarlos
com.sqlmap.User MiUsuario = null;
JSONObject json = (JSONObject) ObjectSerializer.decode(JSON_STRING, ObjectSerializer.JSON_METHOD);
JSONArray array = json.getJSONArray("usuarios");
int numero = array.length();
for (int i=0;i<numero;i++)
{
JSONObject usuario_interno = array.getJSONObject(i);
String id=usuario_interno.getString("login");
System.out.println("usuario interno: "+id);
}
String login = (String) json.get("login");
System.out.println("usuario principal:"+login);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
//end of class ObjectSerializer.java

En el ejemplo instancio una clase User, y relleno algunos de sus atributos (no te proporciono el codigo de esta clase, pero puedes usar cualquiera de las tuyas).

Al convertirlo a XML obtenemos algo como lo siguiente:


<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_08" class="java.beans.XMLDecoder">
<object class="com.sqlmap.User">
<void property="login">
<string>superpiwi</string>
</void>
<void property="password">
<string>superpiwi</string>
</void>
<void property="profile">
<string>Usuario</string>
</void>
<void property="sid">
<string>00001</string>
</void>
<void property="usuarios">
<object class="java.util.Vector">
<void method="add">
<object class="com.sqlmap.User">
<void property="login">
<string>jose</string>
</void>
<void property="password">
<string>jose</string>
</void>
<void property="profile">
<string>Usuario Jose</string>
</void>
<void property="sid">
<string>00001-01</string>
</void>
</object>
</void>
<void method="add">
<object class="com.sqlmap.User">
<void property="login">
<string>soledad</string>
</void>
<void property="password">
<string>soledad</string>
</void>
<void property="profile">
<string>Usuario Soledad</string>
</void>
<void property="sid">
<string>00001-02</string>
</void>
</object>
</void>
</object>
</void>
</object>
</java>

Si lo codificamos como un String JSON obtenemos lo siguiente:


{"phone":"","password":"superpiwi","sid":"00001","login":"superpiwi","description":"","project":"","usuarios":[{"phone":"","password":"jose","sid":"00001-01","login":"jose","description":"","project":"","usuarios":null,"email":"","profile":"Usuario Jose"},{"phone":"","password":"soledad","sid":"00001-02","login":"soledad","description":"","project":"","usuarios":null,"email":"","profile":"Usuario Soledad"}],"email":"","profile":"Usuario"}

En el resto del ejemplo recuperamos los valores de los atributos a partir de la cadena JSON. Si quisieramos mapearlos de nuevo a un objeto tendriamos que implementar un metodo que fuera leyendo los atributos a partir de la cadena y asignandoselos a la clase.
Solo un comentario, para indicar el uso del elemento JSONArray, lo que he hecho en la clase User es tener un vector de usuarios, que voy rellenando con el metodo add, es decir, tengo un usuario principal y un atributo «usuarios» que realmente es un vector de mas usuarios.

Para acceder a un elemento simple empleariamos el JSONObject, pero para acceder a esta lista de elementos (que a su vez son JSONObject) empleariamos el JSONArray.

TextArea Mejorado marzo 1, 2007

Posted by superpiwi in Javascript.
add a comment

En http://gregtaff.com/misc/editRegions/ me encuentro un control javascript muy interesante. He modificado el codigo para cambiar el funcionamiento de los botones ya que no funcionaban como yo queria. En principio he añadido una variable que almacena el texto original para recuperarlo cuando se pulse el boton «Cancelar». Y tambien he modificado el texto y funcionamiento de los botones.

textarea01.jpg

Aqui el código (Conectate a la pagina principal del autor, para consultar la licencia de uso).

demo.html


<html>
<head>
<title>EDIT IN PLACE</title>
<script type="text/javascript" src="MouseState.js"></script>
<script type="text/javascript" src="EditRegions.js"></script>
<style type="text/css">
body {width:700px;margin:auto;}
a{color:#41759A;font-weight:bold;text-decoration:none;border-bottom:1px solid #41759A;}
a:visited {color:#820001;border-color:#820001;}
.red{color:black;background:#FCF9D7;font-family:times new roman;padding:10px;margin:30px;}
.edit_edit {background:#FFF;margin:0px;padding:2px;color:#000;}
.editButtons {
background:gray;
float:left;
padding:0px 4px;
margin:2px;
color:#FFF ! important;
text-Decoration:none;
font-Size:.8em;
fontFamily:Arial, Helvetica, sans-serif;
}
.editButtons:hover {
background:#000;
color:#FFF;
}</style>
</head>
<body>
<div style="background:#D4F6FF;padding:10px;min-height:310px;margin-bottom:30px;" >
<b>DEMO TEXTAREA MEJORADO:</b>
<br/>Codigo original de <a href='http://gregtaff.com/misc/editRegions/'>http://gregtaff.com/misc/editRegions/ </a>
<br/>Modificaciones por Jose Delgado, 1 de Marzo 2007
<br/><br/>
<li> Modificado el javascript EditRegions para guardar el texto original del textarea en una variable</li>
<li> Modificado el codigo de los botones para Guardar el texto, recuperar el texto original o limpiar el textarea</li>
<div class="editInPlace red" style="float:right;width:300px;">
Este control sirve para mejorar la apariencia en las cajas de texto que se usan para mostrar descripciones. Click sobre la barra gris para mover el control y click en el ultimo boton para redimensionar. Escribe aqui tu descripcion...
</div></body>
</html>

EditRegions.js

/*
documentation... do to
KEYBOARD SHORTCUTS
[escape] will cancel edit.
[alt][ctrl][s] will save.
*/
function $() {
//
// Just a shortened version of document.getElementById();
// shamelessly ripped from prototype.
//
var results = [], element;
for (var i = 0; i < arguments.length; i++)
{
element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
results.push(element);
}
if(results.length == 1){return results[0]}
return results;
}
function getStyle(el,styleProp)
// notes: retrieves the rendered style attribute [styleProp] of the element [el]
// Equivalent to el.currentStyle[styleProp] in IE and
// document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp)
// in W3C compliant browsers.
// credit: http://www.quirksmode.org/dom/getstyles.html
{
var x = el;
if(typeof x == "string"){x = document.getElementById(x);}
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
var InPlace = {
elems: new Object(),
createButton: function(caption, ordinal, clickEvent)
{
var thisButton = document.createElement("a");
thisButton.style.position="absolute";
thisButton.style.cursor="pointer";
thisButton.style.display="none";
thisButton.className = "editButtons";
thisButton.href="#";
thisButton.ordinal = ordinal;
thisButton.innerHTML = caption;
thisButton.id = "editButton" + caption + ordinal;
thisButton.onclick = clickEvent;
return thisButton;
},
editButtons: {
hideButtons:function(ordinal){
for(buttons in InPlace.elems[ordinal]["buttons"]){
InPlace.elems[ordinal]["buttons"][buttons].style.display = "none";
}
},
showButtons:function(ordinal){
var xLocation = 1;
for(button in InPlace.elems[ordinal]["buttons"])
{
InPlace.elems[ordinal]["buttons"][button].style.display = "";
InPlace.elems[ordinal]["buttons"][button].style.top = InPlace.elems[ordinal]["edit"].offsetHeight+1;
InPlace.elems[ordinal]["buttons"][button].style.left = xLocation;
xLocation = xLocation + InPlace.elems[ordinal]["buttons"][button].offsetWidth + 2;
}
}
},
initialize: function(tagName)
// notes: find elements of the specified type [tagName]
// cycle through them and find elements in the editInPlace class.
//
// for each found element, create two elements.
// Id them 'editDisplayX' and 'editEditX' where X is the array index.
//
// ensure that each item will display properly, then assign the appropriate behaviors.
// copy content from the original element into the display item and append the two new
// items to the now empty original element - which will then act as a wrapper.
{
if(!tagName){tagName = "*"}
var eipItems = document.getElementsByTagName(tagName);
var itemsCtr
for(itemsCtr = 0; itemsCtr<eipItems.length; itemsCtr++){
if(eipItems[itemsCtr].className.indexOf("editInPlace") != -1){
this.makeEditable(eipItems[itemsCtr], itemsCtr);
}
}
},
beginEdit:function(ordinal)
{
var lastButton = this.elems[ordinal]["buttons"][this.elems[ordinal]["buttons"].length - 1];
this.elems[ordinal]["edit"].style.display = "";
this.elems[ordinal]["displayBorder"].style.display = "";
this.elems[ordinal]["editBorder"].style.display = "";
this.elems[ordinal]["resize"].style.display = "";
this.editButtons.showButtons(ordinal);
this.elems[ordinal]["displayBorder"].style.height = this.elems[ordinal]["display"].offsetHeight;
this.elems[ordinal]["displayBorder"].style.width = this.elems[ordinal]["display"].offsetWidth;
this.elems[ordinal]["displayBorder"].style.top = this.elems[ordinal]["display"].offsetTop;
this.elems[ordinal]["displayBorder"].style.left = this.elems[ordinal]["display"].offsetLeft;
this.elems[ordinal]["editBorder"].style.height = this.elems[ordinal]["edit"].offsetHeight + this.elems[ordinal]["buttons"][1].offsetHeight + 6;
this.elems[ordinal]["editBorder"].style.width = this.elems[ordinal]["edit"].offsetWidth;
this.elems[ordinal]["resize"].style.width = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["resize"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["resize"].style.left = this.elems[ordinal]["edit"].offsetWidth - this.elems[ordinal]["buttons"][0].offsetHeight - 3;
this.elems[ordinal]["resize"].style.height = this.elems[ordinal]["resize"].offsetWidth;
this.elems[ordinal]["move"].style.width = this.elems[ordinal]["edit"].offsetWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 7);
this.elems[ordinal]["move"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["move"].style.left = lastButton.offsetLeft + lastButton.offsetWidth + 2;
this.elems[ordinal]["move"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["edit"].focus();
},
finishEdit:function(ordinal, success)
{
this.elems[ordinal]["edit"].style.display="";
this.elems[ordinal]["display"].style.display="";
this.elems[ordinal]["displayBorder"].style.display = "none";
this.elems[ordinal]["editBorder"].style.display = "none";
this.elems[ordinal]["resize"].style.display = "none";
this.editButtons.hideButtons(ordinal);
if(success){
if(navigator.product != 'Gecko'){this.elems[ordinal]["display"].innerHTML=this.elems[ordinal]["edit"].value.replace(/[\r]/gi,"<br\/>")}
if(navigator.product == 'Gecko'){this.elems[ordinal]["display"].innerHTML=this.elems[ordinal]["edit"].value.replace(/[\r\n]/gi,"<br\/>")}
}
else{
this.elems[ordinal]["edit"].value = this.elems[ordinal]["display"].innerHTML.replace(/[\n\r]/gi,"");
this.elems[ordinal]["edit"].value = this.elems[ordinal]["edit"].value.replace(/<br>/gi,"\r").replace(/<br\/>/gi,"\r");
this.elems[ordinal]["edit"].value = this.elems[ordinal]["edit"].value.replace(/\r\s/gi,"\r").replace(/\x20+/gi," ");
}
},
makeEditable: function(thisItem, ordinal)
{
var displayElm = thisItem;
displayElm.className = thisItem.className.replace(/editInPlace/, "edit_display");
displayElm.ordinal = ordinal;
displayElm.style.cursor = "pointer";
displayElm.onclick = function()
{
window.eval(this.parentNode.getAttribute("onedit"));
InPlace.beginEdit(this.ordinal);
}
var editElm = document.createElement("textarea");
// retouch the value so it will display consitantly between HTML and the textarea.
editElm.value = thisItem.innerHTML.replace(/[\n\r]/gi,"");
editElm.value = editElm.value.replace(/<br>/gi,"\r").replace(/<br\/>/gi,"\r");
editElm.value = editElm.value.replace(/\r\s/gi,"\r").replace(/\x20+/gi," ");
editElm.style.width = thisItem.offsetWidth;
editElm.style.height = thisItem.offsetHeight;
editElm.style.display="none";
editElm.style.border="0px solid black";
editElm.className = "edit_edit";
editElm.id = "editEdit" + ordinal;
editElm.ordinal = ordinal;
editElm.onupdate =function() {window.eval(this.parentNode.getAttribute("onupdate"));}
editElm.onkeypress = function(e){
pressedKey = e ? Math.max(e.keyCode, e.charCode) : window.event.keyCode;
ctrlKey = e ? e.ctrlKey : window.event.ctrlKey;
altKey = e ? e.altKey : window.eventaltKey;
if((pressedKey == 115 || pressedKey == 83) && ctrlKey && altKey){
InPlace.finishEdit(this.ordinal, true)
this.onupdate();
return false;
}
if(pressedKey == 27){
InPlace.finishEdit(this.ordinal, false)
return false;
}
}
editElm.onkeyup = function(e){
var ordinal = this.ordinal;
if(navigator.product != 'Gecko'){InPlace.elems[ordinal]["display"].innerHTML=InPlace.elems[ordinal]["edit"].value.replace(/[\r]/gi,"<br\/>")}
if(navigator.product == 'Gecko'){InPlace.elems[ordinal]["display"].innerHTML=InPlace.elems[ordinal]["edit"].value.replace(/[\r\n]/gi,"<br\/>")}
InPlace.elems[ordinal]["displayBorder"].style.height = InPlace.elems[ordinal]["display"].offsetHeight;
InPlace.elems[ordinal]["displayBorder"].style.width = InPlace.elems[ordinal]["display"].offsetWidth;
InPlace.elems[ordinal]["displayBorder"].style.top = InPlace.elems[ordinal]["display"].offsetTop;
InPlace.elems[ordinal]["displayBorder"].style.left = InPlace.elems[ordinal]["display"].offsetLeft;
}
var displayBorderElm = document.createElement("div");
var editBorderElm = document.createElement("div");
var resizeElm = document.createElement("div");
var moveElm = document.createElement("div");
displayBorderElm.style.position = "absolute";
displayBorderElm.style.border = "1px dashed red";
displayBorderElm.style.display = "none";
editBorderElm.style.position = "absolute";
editBorderElm.style.border = "1px solid black";
editBorderElm.style.background = "#FFF";
editBorderElm.style.display = "none";
editBorderElm.style.top = displayElm.offsetTop; // + displayElm.offsetHeight;
editBorderElm.style.left = displayElm.offsetLeft;
resizeElm.style.position = "absolute";
resizeElm.style.background = "gray";
resizeElm.style.fontSize = "0em";
moveElm.style.position = "absolute";
moveElm.style.background = "#C6C6C6";
moveElm.style.fontSize = "0em";
moveElm.onmousedown = function(e){InPlace.startMove(e,ordinal)};
resizeElm.onmousedown = function(e){InPlace.startSize(e,ordinal)};
// populate our object structure
this.elems[ordinal] = new Object();
this.elems[ordinal]["edit"] = editElm;
this.elems[ordinal]["display"] = displayElm;
this.elems[ordinal]["displayBorder"] = displayBorderElm;
this.elems[ordinal]["editBorder"] = editBorderElm;
this.elems[ordinal]["resize"] = resizeElm;
this.elems[ordinal]["move"] = moveElm;
this.elems[ordinal]["buttons"] = new Array();
//-------------------------------------------------------------------------------------------
// @MODIFICATION 1 Marzo - jdelgado
// Se añade nuevo para guardar el texto anterior y recuperarlo si se pulsa el boton CANCEL
// Se modifica el texto y el codigo de los botones
//-------------------------------------------------------------------------------------------
this.elems[ordinal]["texto_origen"] = editElm.value;
//thisItem.innerHTML;
this.elems[ordinal]["buttons"].push( this.createButton("Guardar", ordinal,
function()
{
// Se guarda, actualizamos el contenido del texto_origen
InPlace.elems[ordinal]["texto_origen"]=InPlace.elems[ordinal]["edit"].value;
InPlace.finishEdit(this.ordinal, true);
$("editEdit"+this.ordinal).onupdate();
return false;
}
)
);
this.elems[ordinal]["buttons"].push( this.createButton("Cancelar", ordinal,
function()
{
InPlace.elems[ordinal]["edit"].value=InPlace.elems[ordinal]["texto_origen"];
//InPlace.finishEdit(this.ordinal, false);
return false;
}
)
);
this.elems[ordinal]["buttons"].push( this.createButton("Eliminar", ordinal,
function()
{
InPlace.elems[ordinal]["edit"].value="";
//InPlace.finishEdit(this.ordinal, false);
return false;
}
)
);
//--------------------------------------------------------------------------------
// FIN DE LA MODIFICACION
//--------------------------------------------------------------------------------
// finally, attach the elements.
document.getElementsByTagName('body')[0].appendChild(displayBorderElm);
document.getElementsByTagName('body')[0].appendChild(editBorderElm);
editBorderElm.appendChild(editElm);
editBorderElm.appendChild(resizeElm);
editBorderElm.appendChild(moveElm);
for(buttons in InPlace.elems[ordinal]["buttons"]){
editBorderElm.appendChild(InPlace.elems[ordinal]["buttons"][buttons]);
}
},
sizeProc: null,
moveProc: null,
startMove: function(e,ordinal)
{
if (!e) var e = window.event;
if (!e.target) e.target = e.srcElement;
var offsetX = (e.offsetX) ? e.offsetX : e.layerX;
var offsetY = (e.offsetY) ? e.offsetY : e.layerY;
offsetX += e.target.offsetLeft;
offsetY += e.target.offsetTop;
eventObserve(document, 'mousemove', MouseState.onmousemove);
eventObserve(document, 'mouseup', InPlace.endMove);
this.moveProc = eventObserve(document, 'mousemove', function(e){InPlace.doMove(e,ordinal, offsetX, offsetY)});
},
doMove: function(e,ordinal,offsetX,offsetY)
{
this.elems[ordinal]["editBorder"].style.top = MouseState.y - offsetY;
this.elems[ordinal]["editBorder"].style.left = MouseState.x - offsetX;
},
endMove: function(e,ordinal)
{
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
eventStopObserving(document, 'mousemove', InPlace.moveProc);
eventStopObserving(document, 'mouseup', InPlace.endMove);
},
startSize: function(e, ordinal)
{
if (!e) var e = window.event;
if (!e.target) e.target = e.srcElement;
var insideOffsetX = (e.offsetX) ? e.offsetX : e.layerX;
var insideOffsetY = (e.offsetY) ? e.offsetY : e.layerY;
var targetWidth = e.target.offsetWidth;
var targetHeight = e.target.offsetHeight;
offsetX = e.target.parentNode.offsetLeft - (targetWidth - insideOffsetX) - 2;
offsetY = e.target.parentNode.offsetTop - (targetHeight - insideOffsetY) - 2;
var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
var dsocleft=(navigator.product != 'Gecko')? iebody.scrollLeft : pageXOffset
var dsoctop=(navigator.product != 'Gecko')? iebody.scrollTop : pageYOffset
MouseState.x = e.clientX + dsocleft;
MouseState.y = e.clientY + dsoctop;
eventObserve(document, 'mousemove', MouseState.onmousemove);
eventObserve(document, 'mouseup', InPlace.endSize);
this.sizeProc = eventObserve(document, 'mousemove', function(e){InPlace.doSize(e,ordinal, offsetX, offsetY)});
},
doSize: function(e,ordinal,offsetX,offsetY)
{
this.elems[ordinal]["editBorder"].style.height = MouseState.y - offsetY;
this.elems[ordinal]["editBorder"].style.width = MouseState.x - offsetX;
var lastButton = this.elems[ordinal]["buttons"][this.elems[ordinal]["buttons"].length - 1];
editHeight = (MouseState.y - offsetY) - this.elems[ordinal]["buttons"][1].offsetHeight -6;
editWidth = (MouseState.x - offsetX) - 2;
MoveWidth = editWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 6)
if(editHeight < 80){
MouseState.y = (80 + lastButton.offsetHeight + 6) + offsetY;
this.elems[ordinal]["editBorder"].style.height = 80 + lastButton.offsetHeight + 6;
}
if(MoveWidth < this.elems[ordinal]["buttons"][0].offsetHeight){
MouseState.x = (this.elems[ordinal]["move"].offsetLeft + (lastButton.offsetHeight * 2) + 6) + offsetX;
this.elems[ordinal]["editBorder"].style.width = this.elems[ordinal]["move"].offsetLeft + (lastButton.offsetHeight * 2) + 6;
}
this.elems[ordinal]["edit"].style.height = (MouseState.y - offsetY) - this.elems[ordinal]["buttons"][1].offsetHeight -6;
this.elems[ordinal]["edit"].style.width = MouseState.x - offsetX - 2;
this.elems[ordinal]["resize"].style.width = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["resize"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["resize"].style.left = this.elems[ordinal]["edit"].offsetWidth - this.elems[ordinal]["buttons"][0].offsetHeight - 1;
this.elems[ordinal]["resize"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.elems[ordinal]["move"].style.width = this.elems[ordinal]["edit"].offsetWidth - (lastButton.offsetLeft + lastButton.offsetWidth + this.elems[ordinal]["resize"].offsetWidth + 5);
this.elems[ordinal]["move"].style.top = this.elems[ordinal]["edit"].offsetHeight + 3;
this.elems[ordinal]["move"].style.left = lastButton.offsetLeft + lastButton.offsetWidth + 2;
this.elems[ordinal]["move"].style.height = this.elems[ordinal]["buttons"][0].offsetHeight;
this.editButtons.showButtons(ordinal);
},
endSize: function(ordinal)
{
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
eventStopObserving(document, 'mousemove', InPlace.sizeProc);
eventStopObserving(document, 'mouseup', InPlace.endSize);
},
browserResize: function(){
for(ordinal in InPlace.elems){
var changeY = InPlace.elems[ordinal]["displayBorder"].offsetTop - InPlace.elems[ordinal]["display"].offsetTop;
var changeX = InPlace.elems[ordinal]["displayBorder"].offsetLeft - InPlace.elems[ordinal]["display"].offsetLeft;
InPlace.elems[ordinal]["editBorder"].style.top = InPlace.elems[ordinal]["editBorder"].offsetTop - changeY;
InPlace.elems[ordinal]["editBorder"].style.left = InPlace.elems[ordinal]["editBorder"].offsetLeft - changeX;
InPlace.elems[ordinal]["displayBorder"].style.height = InPlace.elems[ordinal]["display"].offsetHeight;
InPlace.elems[ordinal]["displayBorder"].style.width = InPlace.elems[ordinal]["display"].offsetWidth;
InPlace.elems[ordinal]["displayBorder"].style.top = InPlace.elems[ordinal]["display"].offsetTop;
InPlace.elems[ordinal]["displayBorder"].style.left = InPlace.elems[ordinal]["display"].offsetLeft;
}
}
}
eventObserve(window,"load", function(){InPlace.initialize('div')});
eventObserve(window,"resize", function(){InPlace.browserResize()});

MouseState.js


// MouseState.js
// Reports the current "State of the Mouse" upon request
function eventObserve(elm, evType, fn, useCapture) {
//
// Cross-browser friendly means of registering event handlers
// Taken from http://www.dustindiaz.com/top-ten-javascript/
//
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return fn;
}
else if (elm.attachEvent) {
elm['e'+evType+fn] = fn;
elm[evType+fn] = function(){elm['e'+evType+fn]( window.event );}
elm.attachEvent( 'on'+evType, elm[evType+fn] );
//var r = elm.attachEvent('on' + evType, fn);
return fn;
}
else {
elm['on' + evType] = fn;
}
}
function eventStopObserving(elm, evType, fn, useCapture) {
//
// Cross-browser friendly means of unregistering event handlers
// bastardized from prototype event.stopObserving, then formatted to jive with eventObserve
//
if (elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
} else if (elm.detachEvent) {
try {
elm.detachEvent( 'on'+evType, elm[evType+fn] );
elm[evType+fn] = null;
}
catch (e) {}
}
return fn;
}
var buttons = {
//
// mouse buttons
//
left:((navigator.product == 'Gecko')?0:1),
right:((navigator.product == 'Gecko')?2:2),
middle:((navigator.product == 'Gecko')?1:4)
}
var MouseState = {
//
// keeps up to date information about the mouse positions and the clickity click of its buttons.
// watching the mouse move event is pretty intense - resource wise - so turn it off when you
// aren't using it.
//
x: 0,
y: 0,
leftButtonDown: false,
rightButtonDown: false,
middleButtonDown: false,
onmousedown: function(e)
{
if (!e) var e = window.event
MouseState.leftButtonDown = (e.button & buttons.left)?true:false;
MouseState.rightButtonDown = (e.button & buttons.right)?true:false;
MouseState.middleButtonDown = (e.button & buttons.middle)?true:false;
},
onmouseup: function(e)
{
if (!e) var e = window.event
MouseState.leftButtonDown = (e.button & buttons.left)?false:MouseState.leftButtonDown;
MouseState.rightButtonDown = (e.button & buttons.right)?false:MouseState.rightButtonDown;
MouseState.middleButtonDown = (e.button & buttons.middle)?false:MouseState.middleButtonDown;
},
onmousemove: function(e)
{
if (!e) var e = window.event;
var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
var dsocleft=document.all? iebody.scrollLeft : pageXOffset
var dsoctop=document.all? iebody.scrollTop : pageYOffset
MouseState.x = e.clientX + dsocleft;
MouseState.y = e.clientY + dsoctop;
},
captureMove: function(){
eventObserve(document, 'mousemove', MouseState.onmousemove);
},
releaseMove: function(){
eventStopObserving(document, 'mousemove', MouseState.onmousemove);
}
}
eventObserve(document, 'mousedown', MouseState.onmousedown);
eventObserve(document, 'mouseup', MouseState.onmouseup);

Plantillas en JavaScript febrero 28, 2007

Posted by superpiwi in Javascript.
add a comment

Una funcionalidad muy buena de prototype es la de permitirnos usar plantillas en javascript.
Un ejemplo sencillo:

/**

* Devuelve el texto formateado del usuario (utiliza una plantilla de javascript)

* @param user objeto con los datos del usuario

* @return una cadena con los datos del usuario preparados para presentar en formato HTML

*/

function returnar(user)

{

//Ejemplo de plantilla en javascript

var syntax = /(^|.|r|n)(<%=s*(w+)s*%>)/; //matches symbols like '<%= field %>'

var t = new Template('<div>Nombre: <b><%= name %></b>, Email: <b><%=email%></b></div>', syntax);

//a = t.evaluate( {name: 'John Doe', email: 'john@doe.es'} );

return t.evaluate(user);

//alert(a);

}

//----// datos del usuario

usuario = {name: 'John Doe', email: 'john@doe.es'};

user_html = returnar(usuario);

// texto formateado

alert("recuperado:"+user_html);

Al evaluarlo nos devolvera lo siguiente:

Nombre: John Doe, Email: john@doe.es

Documentar el codigo JavaScript febrero 14, 2007

Posted by superpiwi in Javascript.
4 comments

Si necesitas documentar el codigo JavaScript puedes emplear JSDoc.

http://jsdoc.sourceforge.net/

Es una herramienta muy sencilla (eso si, necesitas tener un interprete de perl instalado en la maquina). Para documentar la sintaxis es:

perl jsdoc.pl <tufichero.js>

Ejemplo para el fichero «util.js» con este contenido:


/**
* @fileoverview Libreria con funciones de utilidad
*
* @author jose
* @version 0.1
*/
/**
* Muestra un mensaje de texto
* @param {String} metodo nombre del metodo
* @param {String} mensaje mensaje a mostrar
* @returns {integer} el codigo de retorno 0
*/
function trazas(metodo,mensaje)
{
alert("["+metodo+"]:"+mensaje);
return 0;
}
//--------

Al ejecutar:

perl jsdoc.pl util.js

se generan una serie de ficheros HTML en el directorio con la documentacion de la libreria javascript. El resultado es muy vistoso:

jsdoc.jpg