— Tech+Life+Music

Archive
Code

I found myself having to create a completely REST-enabled API for an in-house solution, so what better way to do this in .NET than leveraging ASP.NET Web API?

So yeah, enabling CORS in Web API

While Web API makes mostly everything about the process simple and easy, considering that this is going to be a full-fledged REST API, I had to consider allowing cross-domain requests to the API, which normally meant that I had to enable cross-origin resource sharing (CORS) on it.

I found a nice handful of good resources for ASP.NET Web API CORS support, but I found Carlos Figueira’s take on it the most helpful, so I went ahead and adapted his code into my own small AOP library for use with future projects.

Using the library should be as easy as just adding [CorsEnabled] on your API actions and/or controllers. It provides a bit of additional functionality if you need it (like specifying allowed domains if you want).

Feel free to get the code here. I wholeheartedly welcome comments on it, and if you find that you want to fork it, be my guest.

Read More

A sample project for this discussion is available over on my Github.

There are countless use cases where I found myself needing to use Razor syntax (in ASP.NET MVC 3+) inside Javascript, CSS and other asset files. While there are many different ways to get Razor output into external JS files (for example, getting a Url.Action() call into a JS file’s jQuery.ajax() call), I find that most feel like beating around the bush. After all, views in MVC don’t always have to be HTML files, at least in the traditional spirit of MVC.

So why not create a Javascript view?

If you think about it, there’s nothing really stopping you from creating a controller, adding in a view, then writing up the view in Javascript syntax (save for the less-than-tasty syntax highlighting and Intellisense in Visual Studio, since it kind of expects that views are HTML files).

The key thing is to modify the Content-Type of the response to the appropriate value, based on what you’re returning. So Javascript files will be text/javascript, CSS files will be text/css. It’s the same basic idea with, for example, returning image data through the wire.

For example, this controller action:

public class AssetController : Controller {
 
    public ActionResult Styles () {
 
        Response.ContentType = "text/css";
 
        var model = Context.GetEntity();
        return View(model);
    }
}

… can have the following view:

@model Entity;
 
#entity {
    color : @Model.Color;
    background : url(@Model.BackgroundImage.Url);
}

… and can be wired into your markup just like any other stylesheet:

<link rel="stylesheet" href="@Url.Action("Styles","Asset")" />

Taking all that a bit further, we can write up an Attribute to easily maintain the corresponding Content-Type to each action:

public class ContentType : FilterAttribute, IActionFilter 
{
    private string contentType;
    public ContentType (string ct) {
        this.contentType = ct;
    }
 
    public void OnActionExecuted(ActionExecutedContext context) { /* nada */ }
    public void OnActionExecuting(ActionExecutingContext context) {
        context.HttpContext.Response.ContentType = this.contextType;
    }
}

… and just mark our actions with it:

[ContentType("text/css")]
public ActionResult Styles() {
    // ...
    return View();
}

All that notwithstanding though, you’ll still have to deal with two problems when you do this:

  1. Visual Studio assumes that all views are HTML. You don’t get accurate color highlighting and Intellisense in your asset views. I don’t know about you, but the countless ways that VS pushes back when I do this kind of irks me off.
  2. You don’t get bundling (in ASP.NET MVC 4), and unless you wire it up somehow with WebGrease, you don’t get minification either. Caching is possible, but the whole point of dynamic assets are just that: they’re dynamic. You still can cache via normal ASP.NET MVC methods if, for example, you can manage to scope your use cases into unique URLs (via query strings probably), or you could opt to write your own caching mechanism for this.

If you want to try this out, I’ve prepared a very simple VS 2012 MVC 4 project ready to go over on my Github. Feel free to clone, fork, and/or contribute!

With all that said and done though, I believe that this is the way to correctly use views in an MVC framework, and that Visual Studio should perhaps allows for better leniency for use cases such as this. I’d love to hear your ideas on the topic though.

Read More

If you want to use the LESS dynamic CSS language in your .NET web applications, using the dotless (formally .less) library is the popular way to go, so that your .less files are compiled server-side.

While dotless provides a no-brainer way to serve compiled .less files through its custom HttpHandler, this still forces the app to compile the .less files on every request (barring caching, etc). An arguably better way would be to pre-compile our .less files beforehand, so that we can work with LESS in development, while mindlessly serving minified CSS files in production.

This post will show how we can integrate the dotless package into your .NET web application, do all that crap I just described above, and making sure we do them in an automatic manner. A true set-and-forget system.

Major props go to my colleague @camemay, whose work I’ve built upon.

Let’s get started!

Installing the dotless package

For this post, I’ll be using an ASP.NET MVC 3 web application as a scapegoat. Having a ready MVC 3 project in hand (a new one off Visual Studio would be fine), installing dotless is a breeze over NuGet.

install-package dotless

This does a few things off the bat, but aside from the usual auto-adding of installed assemblies, the changes of more concern are those that silently happened in your web.config:

  • The custom LessCssHttpHandler was registered in your httpHandlers declaration to handle *.less files.
  • The same handler was also registered against the system.webServer declaration.
  • A custom dotless configuration was defined, and a preliminary dotless config section was appended at the end of the file.

Let’s start by modifying the path="*.less" declarations (in two places) to path=".less.css". This allows us to open LESS files in Visual Studio automatically as CSS files, and therefore with CSS Intellisense. Take note that this modifies the handling declarations such that .less files won’t be handled by the dotless handler (they won’t be compiled!) — you have to write your LESS code in .less.css files.

If you’re particularly paranoid about it, you may opt to change verb="GET" to verb="GET,HEAD" as well.

<system.web>
    <!-- ... -->
    <httpHandlers>
        <add path="*.less.css" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
    </httpHandlers>
</system.web>
<system.webServer>
    <!-- ... -->
    <handlers>
        <add name="dotless" path="*.less.css" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
    </handlers>
</system.webServer>

Setting up the automated LESS compilation script

Now that we’ve basically decided that LESS CSS code will be in *.less.css files, we can target that for automatic compilation.

The way we’re going to approach this is by writing a custom MSBuild script that executes the dotless compiler against *.less.css files, converting the LESS syntax to minified legal CSS, and renaming the files to *.min.css. These will be our files for production.

For most of this process, I’ve been referencing Ted Nyberg’s own post on the topic, with a few changes here and there.

Include the dotless compiler in your project

First thing we have to do is to include the dotless.compiler.exe in the project so we can refer to it later in the build script. If you followed this guide and installed dotless via NuGet, then this file will be in $(ProjectDir)/packages/dotless.x.x.x/tool. Just add this executable into your project. For purposes of this guide, I’ll be mirroring Ted’s folder naming convention as well, so I’ll be adding this into an [MSBuild] folder.

Write the build script to compile LESS

Next we’ll start writing our build script. I added an XML file into my [MSBuild] folder, and named it dotless.CompileLessToCss.targets. You can name it whatever you want, but by nature of what we’re going to be working with, a good practice is to name it as a *.targets file.

Let’s start with Ted’s script, and let’s work from there:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
  <Target Name="CompileDotlessCss">
    <ItemGroup>
      <Binaries Include="*.dll;*.exe"/>
    </ItemGroup>
 
    <!-- Compile dotLess CSS into minified full CSS -->
    <Exec Command="$(ProjectDir)..\[MSBuild]\dotless.Compiler.exe $(ProjectDir)..\css\main.css $(ProjectDir)..\css\main.min.css -m"/>
 
  </Target>
</Project>

This script will compile only one file in our project: main.css into main.min.css. Let’s modify this so that it’ll convert all *.less.css in our $(ProjectDir)..\css\ folder into their *.min.css counterparts.

We’ll have to make the build script identify all those *.less.css files. We can set up an ItemGroup declaration to do just that. Put this right before the <Target> declaration:

<ItemGroup>
    <LessFiles Include="css\*.less.css" />
</ItemGroup>

That aside, we can modify the Exec command to this:

<Exec Command="[MSBuild]\dotless.compiler.exe -m %(LessFiles.FullPath)" />

This will take care of running the dotless compiler against all our *.less.css files. Only thing left to do is to specify what filename to use for the compiled + minified CSS code (and not rely on the compiler’s defaults).

Unfortunately, there’s no easy way to call a string.replace on LessFiles.FullPath. I’m personally using the method described in this StackOverflow answer, but there are others suggested on the same page. Use the method most comfortable for you. This modifies my command to this:

<Exec Command="[MSBuild]\dotless.compiler.exe -m %(LessFiles.FullPath) $([System.String]::Copy('%(LessFiles.FullPath)').Replace('.less.','.min.'))" />

Lastly, add the AfterTargets="AfterBuild" property to the Target tag. This will tell MSBuild to run this script after the AfterBuild “event” in the project build process.

Our final build script will be as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">
    <!--    
    This MSBuild Script will compile all [*.less.css] files in the /CSS folder to their [*.min.css] counterparts.
    -->
    <ItemGroup>
        <LessFiles Include="css\*.less.css" />
    </ItemGroup>
    <Target Name="CompileDotlessCss" AfterTargets="AfterBuild">
        <ItemGroup>
            <Binaries Include="*.dll;*.exe"/>
        </ItemGroup>                
 
        <!-- Compile dotLess CSS into minified full CSS -->
        <Exec Command="[MSBuild]\dotless.compiler.exe -m %(LessFiles.FullPath) $([System.String]::Copy('%(LessFiles.FullPath)').Replace('.less.','.min.'))" />
 
    </Target>
</Project>

Invoking our script when the project builds

The last thing we have to do is to make sure our script gets run when the project actually builds. I’m not at all adept with MSBuild (crash courses! ugh!) so you might prefer doing this another way, but this is the method I found closest to heart. Feel free to adjust.

The .csproj file that defines your web application also has MSBuild instructions on how to build it on compile. We’ll just manually plug in directions to include our script.

To be able to edit the .csproj, we’ll first need to unload the project. Right-click on the project in your Solution Explorer, and choose to Unload Project.

With your project unloaded, right-click on the project again, and choose to edit it. You’ll be presented with delicious XML.

Somewhere in all that XML, just plug in an Import command:

<Import Project="[MSBuild]\dotless.CompileLessToCss.targets" />

I’m particularly paranoid, so I put this somewhere towards the end of the file.

And that’s it!

If we did everything correctly, our project should automatically compile our *.less.css into *.min.css whenever we build the project.

Try it out! Add a style.less.css into your project, and slap this inside:

@foo : #beefff;
 
body {
    background : @foo;
    div#main {
        padding : 2px;
    }
}

Compile your project, then navigate to style.less.css in your browser, and you should get the following:

body {
  background: #beefff;
}
body div#main {
  padding: 2px;
}

Navigating to style.min.css should net you:

body{background:#beefff}body div#main{padding:2px}

Use the *.less.css files for development and debugging, and the *.min.css files for production.

Read More

I’ve had a somewhat extensive experience with jQuery so far. I’ve had the pleasure of reviewing peer jQuery code, mentoring potential web devs, teaching in classroom settings, and bashing heads over on StackOverflow, but one thing I’ve noticed all this time is just how hard it is to make developers do one simple thing in jQuery.

And when I say hard, I mean hard. Convincing jQuery developers to use delegate more in their code has got to be one of the more resilient challenges for someone teaching the jQuery craft.

The problem with the learning part of this (what I think at least) is that for devs coming into jQuery, you see bind() and then you see live(), and immediately think that those’re all you’ll need for working with events. Think about it: how long did it take you to know about delegate() from the time you learned about live()?

There’s a lot of argument for delegate out in the interwebs, and I’ve chucked my share in as well somewhat, but let me offer one more compelling reason to use delegate.

Buff your events with a bit more shine

It’s easy to get lost when working with events in jQuery, even for just the somewhat harmless reason that everything is just so easy to do. For example, consider this:

<ul>
    <li>This</li>
    <li>is</li>
    <li>a</li>
    <li>simple</li>
    <li>list</li>
</ul>
jQuery(function($) {
    // we're assigning an event handler to each li element
    $('li').on('click', function () {
        $(this).toggleClass('selected');
    });
});

One would write this code and probably won’t give it a second look. After all, we’re writing our jQuery in pretty much a good form.

What most don’t realize, however, is that to some degree, this comes with it’s inefficiencies, particularly in the fact that binding an event listener in this way automagically attaches a distinct instance of the handler function to each distinct element in the jQuery wrapped set. That means that, for this particular example, we’re creating five references to a function, because each of the li elements gets its own piece of the pie.

If you’re interested in optimizing your code further, you could do this instead:

jQuery(function($) {
     // we're delegating the event handler here
     $('ul').on('click', 'li', function () {
         $(this).toggleClass('selected');
     });
});

What we’re doing here instead is that we’re assigning one (just one!) reference of the function to the ul element, and we’re telling it to fire it whenever a click occurs in any li inside it (hence, delegating).

Now, at first glance, that may not be much, but you’ll be surprised at how fast the performance hits can add up, to the point that there are arguments that delegate may actually be even more efficient to use in a majority of applications than bind.

It’s a pretty simple thing to do in your jQuery code (now even more so because of the unified on() function), so do keep this in mind whenever you’re writing to optimize your jQuery performance.

Read More

The latest version of jQuery (that is, 1.7.1, or 1.7.x) has been around for a good while already, and the new .on() and .off() functions still come to me as the shiniest new toys that came along with it. Not only are they shorter, more intuitive and better at what they do, but they also promote (generally) accepted jQuery good practice that has been around for quite a while.

What am I talking about?

If you’re any jQuery programmer worth your salt, then you know of, at the very least, .bind() and .live() when it comes to DOM event handling. The main difference being that the former is preferred for present elements, and the latter is “mandatory” for future element handling.

One or two rungs up the jQuery programmer ladder, and you’d know of .delegate() as well. If you actually use it with convicted priority over .live(), then you’re golden. An explanation of why would require a good grasp of how jQuery handles events behind the scenes, followed by a primer on why using .live() is bad.

It’s admittedly a pet peeve of mine. And I’d like to think that the reason why .live() persists so sturdily when .delegate() is most clearly a better choice (aside from the fact that the latter was introduced one major version step later in the jQuery lifetime), is that .live() is so much easier to type.

Isn’t it? I mean look at it.

// live
$('a').live('click', do_backflips);
 
// delegate
$(document).delegate('a', 'click', do_backflips);

Sheer convenience.

.on() and .off()

Which is a big reason why I -heart heart heart- the new .on() and .off() functions in jQuery 1.7.x. It streamlines all your event handling into just two functions, whether or not you’re taking into account present or future elements.

If you’re not familiar, the usage for .on() is like this:

// for present elements
$('a').on('click', do_backflips);
 
// for future elements
$('#container').on('click', 'a', do_backflips);

I’d suggest you also take a look at the official documentation for the on and off functions as well. Pretty spiffy.

What’s really nice is that both versions of .on() map to .bind() and .delegate() respectively, which has the added benefit of simplifying the question of what function to use on any given case, and cleaning up syntax. And, hey, it’s also easy and intuitive to use.

Additionally, .live() has also been deprecated as of jQuery 1.7.x. I quote:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Frankly, one could argue that good practice is being forced down the programmers’ throats. But as it plays on clear improvements on jQuery’s event model, I don’t mind that one bit.

Read More

I’m definitely a sucker for code reuse (as I’d argue all programmers should be).

If you’ve had experience working with setting up WCF services for run-of-the-mill CRUD operations (i.e. adding new entities, getting entities, etc), you know how much of a pain in the behind it is to manually type out code designed to work with a single, specific entity (or aggregate). If you’ve got ten entity types available across your SOA, then you might expect to write at least a service operation tailored for each of them, for each of your CRUD processes.

That’s, in and out of itself, 40 operations that more or less will use the same gist of code.

Reusing CRUD code in WCF services

While your mileage may vary (and in real-life projects, the exact same code across all your operations is significantly unlikely), I’ve had to work with this exact situation a few weeks back (spewing out a Stack Overflow entry in the process) and the eventual solution is spiffy enough not to share.

For a good amount of the time, reusing code just means inheriting a base class, however, in the case of service operations, we can’t tag generic methods / classes (which we really want to use as a base class) as service contracts.

A great workaround, is to utilize three things in writing out your operations: an interface for the contract, a (abstract) base class for the generic methods, and another class to function as the tangible service endpoint.

[ServiceContract]
public interface IPersonServiceContract 
{
    [OperationContract]
    void Add(Person person);
    [OperationContract]
    Person Get(int id);
}
// Entity is our POCO entity base class
public abstract class GenericCrudService<T> where T : Entity
{
    // assuming Entity Framework 4.1 CF
    public void Add(T entity) {
        context.Set<T>().Add(entity);
        context.SaveChanges();
    }
 
    public T Get(int id) {
        return context.Set<T>().Where(x => x.Id == id).FirstOrDefault();
    }
}
// and this will serve as the actual endpoint
public class PersonService : GenericCrudService<Person>, IPersonServiceContract
{
    // no code necessary
}

It’s pretty handy, if you ask me. For all additional endpoints you have to create, all you have to do is write out the service contract via an interface, create the actual endpoint, and have it inherit from the contract and the GenericCrudService using the specific type you need.

Read More

One of the ways you can keep readers engaged to your website content is to make sure that links to external sites open to new tabs (or windows). This way, the material they’re engaged in on your site is not erased, they can switch to the newly opened content, and eventually go back to your content (and hopefully continue what they were doing).

However, as websites grow and scale, it can get a little cumbersome to keep track of all the links and manually mark each of them whether or not they open in a new tab. As a case in point, in WordPress (where it’s supposedly pretty easy to do this already), whenever you add a new hyperlink while writing a new article, you have to tick a checkbox to make it open a new tab.

Wouldn’t it be nice to automatically have links open in a new tab (or don’t)? With a bit of jQuery code, we can.

The Code

If you’re itching to jump straight to the code, then here it is, in all it’s -um- glory. Just copy and paste this into your jQuery-enabled page anywhere in between script tags.

jQuery(function($){
    $('a[href^="http://"]')
        .not('[href*="richardneililagan.com"]')
        .attr('target','_blank');
});

Make sure you substitute your own domain name for the richardneililagan.com in there, and you’re all good to go.

If you want to know how that works, read on.

jQuery Magic

What we want to achieve is that when a link pointing outside of our domain is clicked, the linked content is loaded in a new tab. So it’s pretty clear that we want to filter all the links in our site for all those that point outside our domain.

We can do that using simple jQuery selectors:

    // assuming that our domain is RICHARDNEILILAGAN.COM
    var external_links = 
        $('a[href^="http://"]').not('[href*="richardneililagan.com"]');

The first selector (a[href^="http://"]) simply filters for all the links in our page with href values (the URL it links to) that start with http://. External links, unlike internal ones, require http:// for them to properly work, so it’s a good filter for our purposes.

The second filter .not('[href*="richardneililagan.com]') further filters our links by removing those links that have richardneililagan.com (our domain) in them. We’re assuming here that when a link points to something with richardneililagan.com in it, then its internal.

Now, we actually move to making these links open in new tabs. In semantic HTML, to make a link open in a new window/tab, you just have to give it the target = '_blank' attribute pair. So we’re going to do just that, but by using jQuery to do it for us.

    external_links.attr('target','_blank');

With that, all our external links should have been updated target attributes so that they open in new tabs.

Read More

One of the questions I normally get from jQuery learners (aside from why the hell .bind() doesn’t work on dynamically-added HTML elements) is how to write a jQuery plugin. So for this article, I thought I’d introduce a fairly simple step-by-step walkthrough of creating a jQuery plugin that allows us to make something like this really quickly:

Doing this using vanilla jQuery

Of course, you can pretty much do this just by using plain jQuery, just as you would do with most other jQuery functionality. Something like the following would suffice:

// yeap, I know that this code can be optimized a big deal.
jQuery(function($){
 
    // we create two DIVs which form the two parts of our message box
    var $header = $('<div/>').addClass('header').text('Some header'),
        $message = $('<div/>').addClass('message').text('Some message');
 
    // we add the click handler that makes the message slide up and down
    $header.click(function() { $message.slideToggle('fast'); });
 
    // finally, we stick those two DIVs inside some other element
    $('#foo').append($header).append($message);
 
});

With something like that, you’ve pretty much managed to accomplish the same thing.

However, if we want to be able to reuse that piece of code on several other elements, it’d be a better idea to write out that whole jQuery logic into a plugin, so we can just call on it whenever we want.

The basics of extending jQuery

jQuery exposes two kinds of ways to extend it: one using the $ namespace, and the other using $.fn.

Extending the plain $ object allows you to define new utility functions. Adding a new utility function is as easy as just naming a new property:

// creating the "say" utility function
$.say = function (message) {
    alert (message);
};

We can then use that much like any other function by calling $.say('Bros before hoes.');, and it’ll behave as you’d expect it to.

An arguably more powerful way of extending jQuery is extending $.fn, which allows you to create new functions that act on wrapped objects (like, for example, .addClass()). You create new wrapper methods in much the same way you create utility functions:

$.fn.foobar = function () {
    this.text('foobar');
    return this;
}

Inside a new wrapper function, the this object is set to the jQuery wrapped set that the method was called on. So if $('#foo').foobar(); is called, then this inside foobar() is set to $('#foo'). This way, you can manipulate the elements as you see fit.

One of the things you should make a mental note of is to return the this context after the function resolves, so that your new wrapper method is compatible with jQuery chaining. (That is, you can do something like $('#foo').foobar().addClass('bar');.)

Changing our original jQuery code into a plugin

Now that we’ve got the basics out of the way, it should be fairly straightforward to rewrite our code above into a bit of jQuery plugin functionality. Calling our new method slidingBox() and applying the necessary changes in code, we get something like:

(function($){
 
    $.fn.slidingBox = function (header,message) {
 
        var $header = $('<div/>').addClass('header').text(header),
            $message = $('<div/>').addClass('message').text(message);
 
        $header.click(function() { $message.slideToggle('fast'); });
 
        return this.append($header).append($message);
    };
 
})(jQuery);

With that out of the way, we can then use that just by calling something like $('#foo').slidingBox('This is my header.','This is my message.');. With a bit of CSS styling, you’re more or less ready to go!

If you want a more interactive way of demo-ing the code discussed in this article, or if you want to tinker around with ready-made code a bit, then feel free to wreak havoc on a jsFiddle I prepared especially for this article. It’s got ready jQuery code, and some CSS to boot.

Read More

It’s not unusual to cache reusable components in your pages onto variables so that you don’t have to reselect / reevaluate them every single time you have to do something with them.

Let’s say I had a DIV element that I can append paragraphs onto. (Every) Javascript developer worth his/her salt performs some bit of namespacing to the effect of:

<div id="foo"><!-- BLAH --></div>
var app = {
    foo : $('#foo')
};

This way, whenever I’d want to reference that DIV again, I’ll just have to call it via app.foo. I’m actively refraining from polluting the global namespace with a slew of variables for all the elements I want cached, and I have a ready jQuery element that doesn’t need re-selection every time I want to use it.

Adding in functionality

Now, say that I want to add in the functionality to actually add in the paragraphs into my DIV. I can achieve that by doing something like:

var addParagraph = function (text) {
    var myParagraph = $('<p></p>').text(text);
    app.foo.append(myParagraph);
};

… which is perfectly valid since app.foo is, in itself, a valid jQuery object. Improving on that a bit, I’d personally stick that function into the namespace I created prior, so that I don’t add unnecessary global objects.

var app = {
    foo : $('#foo'),
    addParagraph : function (text) {
        var myParagraph = $('<p></p>').text(text);
        app.foo.append(myParagraph);
    } 
};

Making it even better

That’s good. But if you’re a stickler for code (as I am), you’ll probably be itching to structure the code so that app.foo owns the addParagraph function. It makes better sense to have a function that acts on an object alone to be within scope of said object. I’ve got you.

One way to go about it is something like :

app.foo.addParagraph = function (text) {
    var myParagraph = $('<p></p>').text(text);
    this.append(myParagraph);
};

… and that on its own isn’t exactly bad, as you’re getting exactly what you want done. However, the way I’d recommend it most of the time is by using jQuery’s $.extend() function.

$.extend(app.foo, {
    addParagraph : function (text) {
        var myParagraph = $('<p></p>').text(text);
        this.append(myParagraph);
    }
});

$.extend() isn’t something that a lot of jQuery programmers bother with (at least, I think so), but it accomplishes more or less exactly the same thing. So why, then, should I use the $.extend()?

  1. It’s cleaner and easier to add in multiple functionalities at once.

    If I wanted to add in more stuff, like add, edit and remove paragraph functionalities into my object, my code would most probably end up a mess. Not that it’s not possible, but it’s a bit of a maintainance nightmare to have to code something like

    app.foo.add = function () {};
    app.foo.edit = function () {};
    app.foo.remove = function () {};
    // ... some more functions

    I’d rather see something like

    $.extend(app.foo, {
        add : function () {},
        edit : function () {},
        remove : function () {}
    });

    … and since we’re technically working with a plain JSON object as $.extend()‘s second parameter, it’s perfectly valid to go this path :

    var paragraphFunctions = {
        add : function () {},
        edit : function () {},
        remove : function () {}
    };
     
    $.extend(app.foo, paragraphFunctions);

    Wouldn’t you agree that that’s much easier to look at and take care of?

  2. It’s easier to work with multiple components that share the same functionality.

    Not only is it easier to slap on multiple functionalities on one object, but it’s also easier to slap on the same functionalities onto multiple objects.

    If I had two of those DIVs, then traditionally I’d have to do something like this:

    var app = {
        foo : $('#foo'),
        bar : $('#bar')
    };
     
    app.foo.add = function () {};
    app.foo.edit = function () {};
    app.foo.remove = function () {};
     
    app.bar.add = function () {};
    app.bar.edit = function () {};
    app.bar.remove = function () {};
     
    // yeap, I know that that's kind of a stretch

    A more convenient method would be to cache a JSON object with the common functionalities, and use $.extend to slap those onto the relevant components.

    var paragraphFunctions = {
        add : function () {},
        edit : function () {},
        remove : function () {}
    };
     
    $.extend(app.foo, paragraphFunctions);
    $.extend(app.bar, paragraphFunctions);

    Of course, you could also utilize Javascript prototyping at a lower level to achieve the same thing, but this is a somewhat quicker (and less complex) way of doing that.

You can check out a very rudimentary example of making it all work over on jsFiddle.

Read More

Deferred objects are a new addition to jQuery 1.5, and are meant to strike a cleaner division between executing a task and waiting for the task to complete (and reacting accordingly). In this article, we’ll talk about what deferred objects are and what they can do for you, and finish everything off with a simple example application.

If you’ve worked with Javascript a fair deal, then it’s probable that you’ve run across callback functions before. These are most prevalent in asynchronous operations (AJAX comes to mind, of course), and basically provide a way to execute something when an asynchronous operation completes (e.g. react accordingly when an AJAX operation succeeds or fails).

Let’s take a vanilla pre-jQuery 1.5 AJAX request as an example:

$.ajax({
    url : 'ajaxservice.svc/method',
    data : '{}',
    success : function () { alert('YAY!'); },
    error : function () { alert('gulp!'); }
});

Now, with the advent of deferred objects in jQuery 1.5, all $.ajax() derivatives now return deferred objects, which allow you to do the following:

var $defer = $.ajax({
    url : 'ajaxservice.svc/method',
    data : '{}'
});
 
$defer.success(function () { alert('YAY!'); })
      .error(function () { alert('gulp!'); })
      ;

“So what?”, you may say. Well, if you haven’t noticed, the syntax on registering function callbacks is now more akin to the standard way of registering handlers in jQuery, such as with .click() or even .bind() and .delegate(). This allows us to chain registrations into the more familiar way of doing it in jQuery.

var $defer = $.ajax({
    url : 'ajaxservice.svc/method',
    data : '{}'
}).success(function () { alert('YAY!'); })
  .error(function () { alert('gulp!'); })
  ;
 
$defer.success( function () { /* perform additional operations */ } );

The less-noticed advantage of this syntax (and, in my opinion, it’s greatest boon) is how it enables us to easily slap on multiple handlers onto the task’s result events, just like with the vanilla jQuery events such as .click(). The example above shows just that: we registered two separate function literals as two separate handlers for the success callback of a single AJAX operation.

// remember why we stopped doing this in the first place?
<a onclick="alert('DOM Level 0 click handler!');" href="#">Argh!</a>

The old JSON parameter syntax of registering handlers on AJAX calls only allowed us to slap on one callback per event per call. Of course, we could go and create a function literal that calls all the necessary function handlers, but as systems scale and grow more complex, it gets harder and harder to maintain and keep track of everything that’s expected to happen when something happens.

Taking stuff one notch higher

While deferred objects make it so much easier to attach multiple event handlers on a single asynchronous call, that’s easily eclipsed by the fact that deferred objects also allow you to do the exact opposite: performing a task once several tasks are completed.

Let’s tackle this with a more real-world example. Imagine that we had a web page that makes two AJAX calls: one to get data from the server, and another to get an HTML template markup snippet. What we aim to do is that when the two AJAX calls resolve, we want to get our HTML template, slap the fetched content somewhere in it, and append the result into the current page’s DOM.

var flags = [];
 
var my_handler = function () {
    if (flags.length == 2) {
        // do something with the data and HTML template in flags
    }
};
 
$.ajax({
	url : 'ajax.svc/getdata',
	success : function (m) {
	    flags['data'] = m.d;
	    my_handler();
	}
});
 
$.ajax({
	url : 'ajax.svc/gettemplate',
	success : function (m) {
	    flags['template'] = m.d;
	    my_handler();
	}
});

The code above definitely has a number of improvement points going for it, but it effectively illustrates how we may go about with doing the business case we raised. While the code is easily readable and effectively clear, it suffers from the same problems that scalable applications aim to eliminate: as the code expands and the system grows more complex, we’re looking at maintaining larger and larger blocks similar to that above, and eventually that will just be too difficult to maintain and someone will likely trip up.

Along with deferred objects, jQuery also exposes the new $.when() utility function that takes care of managing tasks similar to the one above.

$.when(
    $.ajax({ url : 'ajax.svc/getdata' }),
    $.ajax({ url : 'ajax.svc/gettemplate' })
).then(function (data, template) {
    // do something with the data and template
});

$.when() accepts any number of deferred objects (which $.ajax() derivatives now return), and automatically attach event handlers to the tasks as a singular collective. The resulting data from each deferred object are mapped to the handler function’s parameters in the same order as they were declared (i.e. the resulting data from $.ajax({ url : 'ajax.svc/getdata' }) is mapped to data in the function literal in the .then() call, and so on).

This construct accepts three primary handlers:

  • .done() – called when all deferred tasks succeed
  • .fail() – called when at least one of the deferred tasks fail
  • .complete() – called as soon as all deferred tasks complete, whether or not they succeeded or not

The .then() is shorthand for declaring both .done() and .fail() : the first parameter takes the on-success callback, while the second takes the on-fail callback.

Creating a deferred object

While $.ajax() derivatives now automatically return a deferred object, you may want to manually create deferred objects in your code for specific purposes.

To create a deferred object, you simply call $.Deferred(). These objects basically have three states: unresolved, resolved and rejected.

Deferred objects start off as unresolved, and are either resolved or rejected based on a task’s outcome. When manually handling deferred objects, you’d want to either call .resolve() or .reject() based on a task’s outcome.

Let’s build our own deferred logic example

To put everything we’ve discussed together, we’ll try to create a very simple system that makes use of deferreds.

We’ll use an application that has three INPUT fields. The user is expected to fill up all three fields, so we want a task to run when all three fields have been completed. For this example, we’re going to use deferred objects to update a simple message when all three fields have been filled up by the user.

To start off, here is our completed application:

Form is incomplete.
First Name
Second Name
Third Name

Let’s get started!

We’ve got three INPUT fields that we want filled, so it makes sense to create three separate deferred objects; one for each field.

var $deferreds = [];
// our INPUTs are inside a DIV#example-pane, so we set the context to that
$('input','#example-pane').each(function(i,e){
    $deferreds[i] = $.Deferred();
});

We then initialize the task to perform once all our deferred objects resolve. In this case, we just want to change the text in a simple SPAN element.

// we use the JS .apply() method to call the $.when() function with the elements
// of an array laid out as the function arguments
$.when.apply(null, $deferreds).then(function(){
    $('#example-pane span').text('complete').css('color','#6d6');
});

Finally, we need to manually resolve our deferred objects at the proper time. In our example, we want to resolve the corresponding deferred object when the value of an INPUT field is changed.

$('input','#example-pane').change(function(){
    var myIndex = $('#example-pane').find('input').index(this);
    $deferreds[myIndex].resolve();
});

… aaaaaaaaaaand we’re done. Our complete code is below:

$(function($){
 
    var $deferreds = [];
 
    $('input','#example-pane')
        .each(function(i,e) {
            $deferreds[i] = $.Deferred();
        })
        .change(function(){
            $deferreds[$('#example-pane').find('input').index(this)].resolve();
        });
 
    $.when.apply(null,$deferreds).then(function(){
        $('span','#example-pane').text('complete').css('color','#6d6');	
    });
 
});

Our example can use some improvements (like caching $('#example-pane') for example), but hopefully it has been a clear illustration of how jQuery deferred objects can work with you in your code.

Read More