sábado, 25 de septiembre de 2010

Pensando el plugging para jQuery

La operación de agregar filas nuevas a la tabla y la operación de ordenarla son diferentes. Entonces serán métodos diferentes?
Este es un ejemplo de uso de la librería jQuery.airtable.js:
<script language="javascript" src="./jquery.js"></script>
<script language="javascript" src="./jquery.airtable.js"></script>
<script>
$(document).ready(function(){
  $("#myTable").airtable({addRows: [['Gomez','Manuel','gm@gmail.com','50.85','http://gm.com/index.html']]});
});
</script>
<table id="myTable">
<thead>
<tr>
 <th>Apellido</th>
 <th>Nombres</th>
 <th>Emilio</th>
 <th>Cuenta</th>
 <th>Web</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
La opción addRows es un array de arrays porque debe manejar varias filas, y cada fila tiene varias celdas.
El método airtable() agrega las filas ordenadas a la tabla y la inicializa para ordenar y la reordena si es necesario. Por lo tanto vamos a dejar un solo método.
Nota: La columna 0 es la primer columna, la columna 1 es la segunda columna, y así siguiendo.
La librería utilizará la opción sortList que indique la columna a ordenar, si es orden ascendente o descendente y el tipo del dato que contiene: integer o string. Por ejemplo [[0,0,'string']] significa que la columna 0 se ordena en forma ascendente(0) y se comparan strings; [[2,1,'integer'],[1,1,'string']] significa que se ordena la columna 2 en forma descendente(1) y se comparan números, si son iguales se fija en el orden de la columna 1 en orden descendente(1) comparando strings. Otro ejemplo: [[0,0,'string'],[1,0,false]]; acá indica que la segunda columna no es comparable(false), porque no tiene un tipo.
Complicado? Intentaré arreglarlo.
Esta es la primer versión de mi librería jQuiery.airtable.js:
(function($) {
  $.fn.airtable = function(opciones_user){

  // OPCIONES
  // Ponemos la variable de opciones antes de la iteración (each) para ahorrar recursos
  opc = $.extend( $.fn.airtable.defaults, opciones_user );
  d= opc.debug;
  // FUNCIONES PRIVADAS
  // agregar filas al final de la tabla
  function addTableRows(table,rows){
    trs=''
    for (r in rows){
      td='';
      td+= Array.join(rows[r],'');
      td= ''+td+'';
      trs+= '\n'+td+'';
    }
    if (d) { alert(trs); }
    if($('tbody', table).length > 0){
      $('tbody', table).append(trs);
    }else {
        $(table).append(trs);
    }
    return;
  }
  // ordenar filas
  function sortRows(rows,orden){
    function sortme(a,b,f){
      ff= {
        'integer': function (a,b){ return a-b; }
        ,
        'string': function (a,b){
              if (a==b) { return 0; }
              v= new Array(a,b);
              v.sort();
              return ((a==v[1])?1:-1);
            }
      };
      fff= ff[f];
      return fff(a,b);
    }
    if (orden.length){
      rows.sort(  function (a,b){
        j=0;
        for (o in orden){
          if (!orden[o][2]) { continue; }   // si el tipo es false, la columna no es ordenable
          if (orden[o][1]){
            j= sortme(b[orden[o][0]],a[orden[o][0]],orden[o][2]);
          } else {
            j= sortme(a[orden[o][0]],b[orden[o][0]],orden[o][2]);
          }  
          if (j) { break; }
        }
        return j;
      });
    }
    return rows;
  }

  // DESARROLLO DEL PLUGGING
// Devuelvo la lista de objetos jQuery
  return this.each( function(){
    var t = $(this);  // convierto this (elemento DOM) a jQuery
    var ar= opc.addRows;  // filas a agregar a la tabla
    n= ar.length;
    if (n>0) {
      // ordeno el array de filas
      ar= sortRows(ar,opc.sortList);
      // inserto en la tabla
      addTableRows(t,ar);
    }
  });

};

  // OPCIONES DEFAULTS
$.fn.airtable.defaults = {
        addRows:      [],
        sortList:     [],   //sin orden
        debug:        false
      };

})(jQuery);

No hay comentarios:

Publicar un comentario