Tag Archive for javascript

HTML5 and Javascript is not a HTML5 Javascript application

Javascript and HTML5 is in everybody’s mouth nowadays, looks like everything is around them: Node.js is wonderful and made what others tried to achieve long time ago, frameworks like knockout.js or backbone.js taught us how to develop MVVM and MVC oriented applications using javascript, jQuery is your everyday tool, and even an major operating system (Windows 8 ) announced their support for native HTML5 and Javascript to develop desktop touch friendly applications.

Javascript has emerged from a mere hacking language as a now mainstream language, now it’s common to see job offers for “javascript frontend (or UI) developers” and almost every website I’ve been involved into requires a lot of interaction using your browser… So, what’s the problem?

The problem is simple, even when we have new frameworks, new IDE’s, new paradigms for HTML and javascript applications I see that most developers still treating javascript as a hacking language, I mean, throwing lines and lines of code into the problem, without any separation or patterns or anything else, they still writing rich interactive application as HTML plus javascript, not as a HTML and javascript application.

A good application is more than code and UI, a good application should follow DRY, KISS, SOLID or whatever other acronym do you want to throw at them. HTML and Javascript applications are more than just HTML with Javascript.

Want to do something better? don’t tread Javascript as a hacking language. Period.

At least an element should be filled validation using jQuery validation

Today I got a nice client side validation request, actually was nice because was a simple and very common use case in form validation. Make sure the user fill at least one of the fields in the form before continue.

Let’s say this is the case:

The user should fill any contact detail to validate the form, sounds simple, and it is! the simple way to solve the issue is just creating a jQuery validator method then simply adding the class to the elements in the same group, using the magic of the special jQuery validator selector :filled would return the number of non empty fields in the group and it’s just matter of falsy or truly. Maybe something like this:

The only problem with this approach is the validation messages, we don’t want to see the same label error message everywhere, we just want to display the error message once. Well, just matter of specify a validation group in jQuery validation, that’s all!

See? nothing to worry about!

Regresando a lo básico – Javascript en ASP.NET

Hace unos días un amigo me preguntó algo curioso:

Necesito que todo lo que entre mi usuario en una caja de texto en ASP.NET se transforme automáticamente a mayúsculas. Se me había ocurrido usar OnTextChanged pero no se que tan efectivo podría resultarme.

Bien, considero que esta es algo así como una pregunta elemental, así que tomemonos el tiempo para analizarla y ver las opciones. Asumamos que no podemos usar ASP.NET Ajax Library, ni ASP.NET Ajax Toolkit. Tomemos en cuenta que tampoco podemos usar algo así como JQuery.

La implementación en ASP.NET que propone nuestro amigo se vería algo así:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"
    Inherits="WebApplication7.WebControls" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="nameText" runat="server"
            OnTextChanged="nameText_TextChanged"
            AutoPostBack="true" />
        <br />
        <asp:Label Id="nameLabel" runat="server" />
        <br />
        <asp:Button ID="acceptButton" runat="server" Text="Accept" />
    </div>
    </form>
</body>
</html>

Y el “codebehind” sería algo simple como esto:

using System;
using System.Web.UI;

namespace WebApplication7 {
    public partial class WebControls : Page {
        protected void Page_Load(object sender, EventArgs e) {
        }

        protected void nameText_TextChanged(object sender, EventArgs e) {
            nameText.Text = nameText.Text.ToUpper();
        }
    }
}

Bien, ASP.NET lo que hace al activar el "AutoPostback" es que en cuanto el control pierde su "focus" se envía la página completa de regreso al server, este procesa el evento (en este caso TextChanged) y regresamos el contenido en mayúsculas. Vemos un par de problemas con este caso en particular, el primero es lo poco "práctico" que es enviar toda la página de regreso solamente para hacer una operación "sencilla" como la es transformar el texto en mayúsculas (si, probablemente hay operaciones más "complejas" en las cuales se necesite hacer tal cosa, pero en este caso no se justifica). Tal operación es fácilmente hecha con un simple script de Javascript.

Cuando comenté esto mi amigo me respondió: hey, pero no estoy usando MVC, puedo usar fácilmente Javascript con ASP.NET?, pues, ¡claro que si!, hay varias maneras. Primero, veamos como sería la función de Javascript en cuestión:

function textToUppercase(sender) {
    if (sender && sender.value) {
        sender.value = sender.value.toUpperCase();
     }
}

Una función simple, nada del otro mundo. Bien, ahora solamente modificamos el TextBox para que luzca algo así:

<asp:TextBox ID="nameText" runat="server" onblur="textToUppercase(this);" />

Listo, con esto podemos elminar el codigo que hacía la misma operación en el server, ya no más postbacks :)

Recuerden, no hay problema si agregamos atributos extras de HTMl a nuestros controles de ASP.NET.

Moraleja: Aprovechen el proceso del lado del browser cliente, no abusen del codebehind. Javascript es su amigo, aprovechenlo. No en vano Microsoft esta invirtiendo tiempo para mejorar el soporte de Javascript y la programación al browser cliente para esta y las próximas versiones de ASP.NET.

SyntaxHighlighter 2.0 Haskell Brush

I know there are a lot of Syntax Highlighter out there, but I love Alex Gorbatchev SyntaxHighlighter 2.0.

I had to write a new brush for Haskell language since I start searching for one without any success, this is my first attempt to make a SyntaxHighlighter Brush (and I just starting learning haskell a few weeks ago).

module sample where
{-
Multiline comments
this is a comment too
-}
isDigit :: Int -> Int
abs | n >= 0 = n
    | otherwise = -n
-- Single line comments allowed

You can get the simple brush here http://gist.github.com/261919

Book review: Learning JQuery

1847196705 No es secreto que Microsoft comienza a abrazar el “Open Source”, nadie pensaba hace unos cuantos meses atrás que JQuery, la framework de código abierto para desarrollo y manipulación del DOM en Javascript, sería “adoptada” por Microsoft hasta que hizo el anuncio que no solamente sería “shipped” con Visual Studio para el desarrollo web junto con el ASP.net AJAX Framework, sino que también sería soportada por Microsoft.

Es de esperar que desde el anuncio muchos programadores de ASP.net comenzaran a experimentar con JQuery y claro, a aprender a usar JQuery. Tutoriales de JQuery hay muchos en la red, la mayoría de ellos orientados a diseñadores web o al usuario esporádico de javascript. Creo personalmente que este libro es un excelente inicio al mundo de JQuery.

Lo bueno de este libro:

  • Sin rodeos, Va directo al grano.
  • Simple, es sumamente práctico para explicar el porqué de algo.
  • Casí un hands on, después de un par de capítulos el lector se siente con la suficiente confianza de usar JQuery y aplicar lo que acaba de aprender.
  • Es sumamente corto y de fácil lectura

Lo malo de este libro:

  • El código ejemplo aunque es muy sencillo, ya esta terminado. Poco hace porque el lector experimente con el código de ejemplo.
  • ¿Qué? los capítulos mas interesantes (los últimos 3) no tienen código ejemplo!
  • En los últimos capítulos se perdió fluidés del relato como lo hacian en los primeros capítulos.

Claro, aconsejo antes de leer este y cualquier otro libro de JQuery, que el lector se empape bastante sobre los conceptos de HTML, hojas de estilo, DOM y Javascript, creo que solo así le podemos sacar lo máximo a JQuery.

En general, le doy al libro una calificación 3/5