10
Feb 11

What if…

What if you we’re able to construct complex HTML fragments in C# with the same ease and readability as you are, using jQuery?

Stuff like…


var list = new cQuery
(
    tag: "ul",
    id: "tags",
    controls: new []
    {
        new cQuery(tag: "li", text: "C#"),
        new cQuery(tag: "li", text: "JavaScript"),

        new cQuery(tag: "li", text: "Markup languages").Append
        (
            new cQuery("ul").Append(new []
            {
                new cQuery("li", text: "XHTML"),
                new cQuery("li", text: "HTML 4"),
                new cQuery("li", text: "HTML 5")
            })
        ),

        new cQuery(tag: "li", text: "CSS")
    }
);

list.Wrap
(
    new cQuery("div").AddClass("horizontal").Append
    (
        new cQuery(new LinkButton { ID = "hidelist", Text = "Hide" }).AddClass("small")
    )
);

PlaceHolder.Controls.Add(list);

I will be releasing my cQuery class shortly. Stay tuned.


10
Feb 11

Syntatic sugar: a different way to do if-statements

Try this one out for size.


var value = "no";

if ({ foo: true, bar: true, yes: true, maybe: true }[value]) // will return false

var value = "bar";

if ({ foo: true, bar: true, yes: true, maybe: true }[value]) // will return true

var validValues = {
    foo: true,
    bar: true,
    yes: true,
    maybe: true
};

if (validValues["bar"]) // will return true

C# you say?


if (new [] { "foo", "bar", "yes", "maybe" }.Contains("bar")) // returns true

var validValues = new []
{
    "foo",
    "bar",
    "yes",
    "maybe"
};

if (validValues.Contains("bar")) // returns true

10
Feb 11

The jQuery template plug-in: implementing complex logic using render-functions

The new jQuery template plug-in is awesome. That being said, the double-curly brace template-tags are not exactly my cup of tea. In a more complex template the tags obscure the markup contained in the template, and implementing logic past simple if/else statements is a pain.

After messing around with the plug-in for a few hours, my head began to hurt from trying to distinguish the markup in my template from the millions of double curly braces.

So I popped an aspirin and began work on an alternative. And here it is…

 

The template



 

The JavaScript

$(function ()
{
    // Define an array of animals to be rendered out by the template
    var animals = [
        { species: "Moose", strength: 8, dexterity: 4 },
        { species: "Sloth", strength: 2, dexterity: 0 },
        { species: "Alpaca", strength: 6, dexterity: 9 },
        { species: "Blobfish", strength: 1, dexterity: 2 },
        { species: "Squirrel", strength: 10, dexterity: 10 }, // Squirrels... crazy dangerous!
        { species: "Badger", strength: 4, dexterity: 6 },
        { species: "Emu", strength: 2, dexterity: 8 }
    ];

    // Compile and cache the template
    $.template("animals_template_compiled", $("#animals_template"));

    // Create a render-function which implements complex logic
    function renderer(animal)
    {
        // If an animals strength is rated higher than 5 and if it's dexterity is rated
        // higher than 3... or if the animal is the insanely dangerous squirrel; return
        // it's name in bold
        if ((animal.strength > 5 && animal.dexterity > 3) || animal.species === "Squirrel")
        return "" + animal.species + "";

        // If not; return it's name without the bold tags
        return animal.species;
    }

    // Render the template
    var output = $.tmpl("animals_template_compiled", animals, { render: renderer });

    // Append the rendered template to the DOM
    $("#animals_template_output").append(output);
});

 

The markup in which to place the output of the template

Be warned!

The animals highlighted will probably tear off your arms

It would be a bad idea to try and pet them

     

    The result

     

    … But you get the point

    I know that the logic contained in the render function is not that complex. But you get the point: complex logic is best expressed in JavaScript and not by using hard-to-read syntax, plastered into HTML.

     

    For the purists

    I am aware that I’m breaking the whole model/view/controller concept by using a function to render out part of the template. But enabling full separation of logic and markup is possible. All you have to do is return a boolean value in the renderer function and update your template a tiny bit.

    Note: the name “renderer” no longer applies since the function is now returning a boolean value. It’s been renamed to “isDangerous” in the following code-examples.

     

    The updated template

    
    
    

     

    The updated JavaScript

    
    function isDangerous(animal)
    {
        if ((animal.strength > 5 && animal.dexterity > 3) || animal.species === "Squirrel")
        return true;
    }
    
    var output = $.tmpl("animals_template_compiled", animals, { isDangerous: isDangerous });
    

    20
    Jan 10

    altAlert, a jQuery plug-in for personalized alert messages without the need to change existing code

    I’ve wanted to write a jQuery plug-in for a long time, but I didn’t want to write one just for the exercise.

    Last night I was messing around with overriding native JavaScript functions – among those the alert-function – and it hit me: why not write a plug-in for jQuery which overrides and personalizes alert messages without the need to change any existing code? And while I was at it, integrate the plug-in with jQuery UI and leverage the functionality of the Dialog widget?

     

    So I did. And here’s what I came up with

    Try me!

    Note: my WordPress theme seems to be interfering with the jQuery UI theme; breaking the styles on the close-button in the dialog.

     

    The plug-in code

    jQuery.altAlert = function (options)
    {
        var defaults = {
            title: "Alert",
            buttons: {
                "Ok": function()
                {
                    jQuery(this).dialog("close");
                }
            }
        };
    
        jQuery.extend(defaults, options);
    
        delete defaults.autoOpen;
    
        window.alert = function ()
        {
            jQuery("<div />", { html: arguments[0].replace(/\n/, "<br />") }).dialog(defaults);
        };
    };
    

     

    And here’s how you use it… it’s pretty simple, really

    $(function ()
    {
        $.altAlert();
    });
    

    After calling the plug-in constructor, all calls to the native alert-function will pop up a jQuery UI dialog instead of the boring standard dialog. Neat, huh?

     

    My plug-in leverages the jQuery UI Dialog widget

    And because my plug-in leverages jQuery UI, my plug-in…

    • inherits solid code that has undergone rigorous testing
    • generates solid markup that has been tested and looks the same in all A-grade browsers
    • fully supports the jQuery UI Themeroller

    On top of that: all the functionality available in the jQuery UI Dialog widget is available in my plug-in. This means that you can override the standard functionality of my plug-in – just like you would, using the jQuery UI Dialog widget – and change it’s default behavior:

    $(function ()
    {
        $.altAlert(
        {
            modal: true,
            closeOnEscape: false,
            title: "Dang!... Stuff happend!",
            buttons: {
                "Ok": function()
                {
                    window.location = "error.html";
                }
            }
        });
    });
    

    In the above example, the code effectively locks down a page, preventing user-input, while the browser loads an error page.

     

    In a few days time…

    I will create a project on Google Code, and put up some live usage-examples… In the meantime; feel free to leave comment and tell me what you think.

     

    Update…

    I’ve added my plug-in to the endless list on the jQuery website. Here’s a direct link.