Wednesday, May 23, 2012

ASP.Net MVC App Structure: Using Cassette For JS and CSS

I can't tell you how many times I remember having to put my finger in one of the holes and wind the tape back in.
I still love these things. I'm not sure why.

What Is Cassette?

Cassette is a bundling and minification tool that is very powerful and extremely easy to implement. Long before MVC4 Beta had bundling and minification, Cassette was already doing it better, IMO.




Advantages Of Using Cassette

  • Easy to debug! Bundling and minification is only performed debug="false" is set in the Web.config. 
  • No more need for @section. There will be no more reason to render a section to your layout to plop your <script/> and <link/> tags in.
  • Tracks JavaScript file dependencies. Cassette uses a nice little comment at the top of each .js file to manage what scripts need to be loaded first.
  • Automatically prevents false caching. We've all seen the issue where we've updated some script file and our browser is just dying to hang on to some old version. Cassette gets around this by appending a hash of the file(s) to the reference URL, so every time you change a file, you're pretty much guaranteed your browser will pull down a new copy, but at the same time unchanged files will remain cached.
  • Handles JavaScript templates. Cassette works well with a variety of JavaScript template providers. It actually creates a script to precompile your templates, renders a script tag that loads that script, and hosts the script. It's very slick, but I'm going to try to focus on just the JS and CSS aspects of Cassette today.

Getting Started With Cassette

First you need to install Cassette. There is a nice quick start guide on their site. Personally, I just right click References in my web project and select Manage NuGet Packages. Then I search online for Cassette and install it. Once it's installed, it will have set up your Web.configs, added references, and added a class file called CassetteConfiguration.cs. 

Once the NuGet package is installed, you're going to want to take a look at CassetteConfiguration.cs. What's going on in here is there are a few method calls to set up the root folders for your scripts, templates ans styles. JavaScript templates are disabled by default. As of this writing, it comes initially set up to minify, but not bundle, JavaScript and CSS when debug="false". You can do a lot from this area, configure bundles via file searches, all sorts of things, set up CoffeeScript, LESS, etc. for that see their documentation. Generally I just do the following:

C# - from CassetteConfiguration.cs

public class CassetteConfiguration : ICassetteConfiguration
{
    public void Configure(BundleCollection bundles, CassetteSettings settings)
    {
        bundles.Add<StylesheetBundle>("Content");
        bundles.Add<ScriptBundle>("Scripts");
    }
}


Your Folder Structure Is Now Free!

Now that Cassette is going to be bundling everything in production, I like to structure my folders for css and JavaScript to mirror my Views directories. So if I have a view that requires a script called /Views/Foo/Bar.html, I'm going to have a JavaScript file at /Scripts/Foo/Bar.js, and maybe a style sheet at /Content/Css/Foo/Bar.css. The world is your oyster now, because once Cassette is done with this, it won't matter where you have your files or how many of them there are, really. Also, for support methods in JavaScript I tend to break them out by their namespace names (for more information on namespacing in JavaScript have a look here).

Where To Place .JS and .CSS References In Markup

I always put my CSS files in the <head/> tag, and my JS file references just before the closing </body> tag. I do this because I want the CSS to be loaded and processed right away so the styles can be applied to the objects in the DOM as soon as possible. I also want my JavaScripts to be one of the last things loaded because most browsers will only pull down two or three external resources at a time, and I don't want all of the images on the page to wait for my JavaScripts to get pulled down, when 99% of the time my JavaScripts aren't even going to be executed until the entire document is ready anyhow.

Razor - _Layout.cshtml


@{
    Bundles.Reference("~/Scripts/jquery.js");
    Bundles.Reference("~/Scripts/jquery-ui.js");
    Bundles.Reference("~/Scripts/foo.js");

    Bundles.Reference("~/Content/Site.css");
    Bundles.Reference("~/Content/themes/jquery-ui.css");
}
<!DOCTYPE html>
<html>
<head>
   <title>@ViewBag.Title</title>
   @Bundles.RenderStylesheets()
</head>
<body>
   @RenderBody()
   @Bundles.RenderScripts()
</body>
</html>


Where Not To Place JavaScript and Styles In Markup

  • Do not use inline scripts, do not use inline styles. I'm not going to get into the "whys" here, becasue that's a whole different post... For now, I'll just leave it at "you want to seperate your styles from your behaviors from your markup". Be unobtrusive.
  • Do not put css or styles in your Partial Views! This is a really common mistake I see. What's going to end up happening here, is you're going to end up loading the same scripts or css twice, which can cause unexpected behavior.
  • Try not to put JavaScript in the <head/> tag if you can avoid it. It's not always avoidable, but for reasons I previously mentioned, put them just before the closing </body> tag.

Setting Up JavaScript File Dependencies For Cassette

This is pretty simple as long as you stay on top of it. What needs to be done here is you need to add a little comment to the top of your JS file referencing any .js files that are prerequisite to that file. For example:

JS - Cassette Reference Example

/// <reference path="Scripts/jquery.js" />

/* be sure to note that above there are three "///"
 * and also the path="" is root relative even without
 * the leading "/". */

$(function(){ 
  alert('Omg, wee! The document is ready!!!11');
});


Referencing Your .js and .css Files With Cassette

This is probably the easiest part of all. In a C# code block in your .cshtml files, I recommend at the top of the file, just as I demonstration in my _Layout.cshtml example above. All you do is just add a line that says Bundles.Reference("~/Path/Your/File.js") for each .js or .css file you want to add into a bundle. The syntax is the same for both .js and .css files. It gets a little trickier if you want to reference an external file, although I'm not sure why you'd want to do that, they do detail referencing external scripts in their documentation.

That's really all there is to it! Now I'd recommend setting debug="true" and "false" in your Web.config and checking the page out in your browser a few times so you can marvel at the differences.

Tuesday, May 22, 2012

Structuring an ASP.Net MVC App

Your way is WRONG!

I'm kidding, I'm kidding... haha. Everyone has their own way to do this, and I'm no exception I guess. After 5-6 MVC projects, I feel like I've come to a formula that really works for me and I wanted to share. I've decided to do a series on my personal rendition of structuring an ASP.Net MVC application. I'm going to focus on the current state of things, which is MVC 3 for now. I'll do MVC 4 again maybe when it's out of beta. It has a lot of nice features that may or may not replace what I'm going to talk about here, so this content may be a bit dated in a few months. Such is tech.

Project Structure

The first thing I like to set up is a project structure with the following projects. For sake of  this series, I'm going to use a parent namespace "NS". The projects I add right off are as follows:

  • NS.sln - the solution file.
    • NS.dll - A class library to house global code and helpers, I always have these, so I feel okay adding it right off.
    • NS.Web.csproj - Our MVC app itself.
    • NS.EF.dll - A class library for our actual data access, for the sake of this series, I'll be using EntityFramework, but it could be anything, really.
    • NS.Data.dll - A class library that will house our model and our data access methods that build them. More on this later.

Project Dependencies

Here's where, IMO, a lot of developers drop the ball. I really don't want my web project to be dependent on Entity Framework, or SQL, or MySQL, or MongoDB, or anything like that. I want a level of abstraction, especially when that sort of abstraction comes so easily. Do to this I set up my project dependencies accordingly. Below is a diagram of how my project reference each other.



Wiring Everything Up

The first thing I do is go into NS.EF and generate my entities using EntityFramework. If you're using something else, I think it's a good idea to flush out your actual database access or ORM or whatever right now. It's clearly a critical piece.

Once that is done it's time to move forward to the UI and work out a Controller Action. I have a requirement to create a page that writes out an unordered list of "Foos" from my data. So I'm going to create a FooController.cs file in my Controllers directory, then I'm going to create an Action on it called "List". I'm also going to create a view file in /Views/Foo called List.cshtml.

Beyond that we need to set up our data access for the controller, and that means hopping back to our NS.Data project and adding and IFooService interface, then implementing it. The important thing here is we don't want any consuming code to be able to create an instance of the IFooService implementation directly, so for our implementation, which I'll call FooService, I'm going to leave the modifier off of it, making it internal, whereas IFooService will obviously be public. So how does the web project create an instance of IFooService if it can't see the implementation? With a little static class I'll call ServiceFactory. ServiceFactory will have a static method on it (also called FooService) that creates a FooService (the implementation) and returns IFooService.

Now we head back to our controller for a little dependency injection: I'm gion to add a protected readonly field to stick an IFooService in and call it IFooService. Then I'm going to add two contuctors, one that accepts my dependency, or IFooService, and other that is parameter-less that creates and passes to the other constructor an IFooService via the ServiceFactory.FooService() method.

Now I'm going to set up a Repository pattern for our actual data access via EF. This is done so we can use dependency injection to test our building of the models in FooService. So to do this, I'm going to add a IFooRepository, a FooRepository (the implementation) and a RepositoryFactory to the NS.EF project in the same manner I created and implemented the Services and ServiceFactory. This repository will be to do all of the accessing of EntityFramework. This way, EF is abstracted out enough we can test without having to mock anything more than just a repository implementation.

I want to state this here: I don't like code generated repository patterns. Sure they might save you a little time up front, but they hardly ever do everything you need them to do, they generate a lot of code you'll never use, and IMO, they don't add any value, if anything they just add one more level of complexity to what is really a simple problem: Getting and setting data in some datasource. The underlying ORM is more than enough, I think.

Once that is done, I'm able to go into my Action method and call my GetFooList() method, which returns a model (housed in NS.Data as well), then return an ActionResult with the proper view and the model we just got.

Below you'll see some pseudo-code to help you get the basic idea.

C# - FooController.cs

public class FooController : Controller
{
   /*
    * our service from NS.Data
    * */
   protected readonly IFooService FooService;

   /* 
    * A little ctor magic for dependency injection. 
    * ServiceFactory is from the NS.Data namespace and 
    * provides static methods for instantiating a new service.
    * */
   public FooController() : this(ServiceFactory.FooService())
   {
   }
   public FooController(IFooService fooService) 
   {
      FooService = fooService;
   }

   /*
    * Here we have our Action method.
    * */
   public ActionResult List() 
   {
      var model = FooService.GetFooList();
      return View("List", model);
   }
}

C# - IFooService.cs (NS.Data)

public interface IFooService
{
   FooListModel GetFooList();
}

C# - FooService.cs (NS.Data)

/* Our actual implementation is going to be left internal
 * (NOT PRIVATE) classes with no specifier are internal.
 * Because we don't want outside code creating instances of 
 * our implementations directly. */
class FooService : IFooService
{
   // our repository dependency.
   protected readonly IFooRepository FooRepository;

   // hot dependency injection.
   public FooService() : this(RepositoryFactory.Foo())
   {
   }
   public FooService(IFooRepository fooRepository)
   {
       FooRepository = fooRepository;
   }
   // do the work of getting the data and building the model.
   public FooListModel GetFooList()
   {
      var model = new FooListModel();
      // get our entities from the Repository.
      var fooEntities = FooRepository.GetFoos();
      /* ... build the model out here from the entities ... */
      return model;
   }
}

C# - ServiceFactory.cs (NS.Data)

public static class ServiceFactory
{   
   /* This is where we're going to get our instance of IFooService
    * from for our Controllers. */
   public static IFooService FooService()
   {
      return new FooService();
   }
   /* this one allows dependency injection */
   public static IFooService FooService(IFooRespository fooRepos)
   {
      return new FooService(fooRepos);
   }
]

C# - IFooRepository.cs (NS.EF)

public interface IFooRepository
{
   FooEntity[] GetFoos();
}

C# - FooRepository.cs (NS.EF)

class FooRepository: IFooRepository
{
   /* In here we're going to do the work of getting 
    * some entities from Entity Framework. I like to
    * return arrays or lists or something that forces me
    * to enumerate my queryable to make sure I don't abuse
    * EntityFramework. */
   public FooEntity[] GetFoos()
   {
        using(var dbcontext = new WhateverEFContext())
        {
            /* do whatever you need to do to get your IQueryable */
            return someQueryable.ToArray(); //make sure you only enumerate ONCE!
        }
   }
}


C# - RepositoryFactory.cs (NS.EF)

public static class RepositoryFactory 
{
   public static IFooRepository Foo()
   {
      return new FooRepository();
   }
}

So this is probably all about as clear as mud now, huh? There is just a LOT to go over. I'd recommend googling some articles on why we should use dependency injection, or why it's a good idea to separate your database access code from your Controller Actions. I'd rather not get into that myself, as it's a lengthy discussion and frankly, most of my friends that read this blog are already all over those concepts, in most cases more so than I am.

When I'm all finished with this series, perhaps I'll put together a sample project and host it somewhere for people to pull down and use. There are still several things that I do in my MVC apps I want to touch on, such as Script and Style location and placement, Bundling and Minification with Cassette, other nice to haves like Logging and Profiling, etc. Probably nothing new to everyone, but I'm hoping someone that reads this finds it helpful at some point.

EDIT: I've changed a few things about the way I've named my namespacing and structured things. I had forgotten to implement a repository pattern on the data access side of things, and that caused the Service implementations to be a bit hard to test. I'm going to try to edit this post to rectify that.

Tuesday, May 15, 2012

Advanced Asynchronus JavaScript Function Call With Event Subscriptions

Per a request for my good friend, Adam Hew, who enjoyed my last post, I've thrown together a quick implementation of an asynchronous function caller with JQuery ajax-esque event subscriptions. 1.7+ of course. ;).  The challenge here was to put together something where multiple subscribers can be notified when the code is complete or if it errors or if it's successful. So here goes:

My Implemention Of An Async Caller With Event Subscription

var async = (function() {
    var AsyncResult = function(caller) {
        // set up some events.
        var completeEvents = [];
        var successEvents = [];
        var errorEvents = [];
        // and some event triggers.
        var onComplete = function() {
            for (var i = 0; i < completeEvents.length; i++) {
                completeEvents[i]();
            }
        }
        var onSuccess = function(result) {
            for (var i = 0; i < successEvents.length; i++) {
                successEvents[i](result);
            }
        }
        var onError = function(err) {
            for (var i = 0; i < errorEvents.length; i++) {
                errorEvents[i](err);
            }
        }
        //a little prep work.
        var self = this;
        this.caller = caller;
        //set up our subscription methods.
        this.complete = function(fn) {
            completeEvents.push(fn);
            return self;
        };
        this.success = function(fn) {
            successEvents.push(fn);
            return self;
        }
        this.error = function(fn) {
            errorEvents.push(fn);
            return self;
        }
        //call the function async and kick off triggers.
        setTimeout(function() {
            try {
                onSuccess(caller());
            } catch (err) {
                onError(err);
            }
            onComplete();
        }, 0);
    };
    return function(fn) {
        return new AsyncResult(fn);
    };
})();

//Now try it out!
async(function() {
    return 2 + 2;
}).complete(function() {
    console.log('complete!');
}).success(function(result) {
    console.log('result is ', result);
}).error(function(err) {
    console.log('ERROR!', err);
});


//or another way (showing multiple subscriptions):
var r = async(function() {
    return 'foo';
});
r.success(function(data) {
    console.log(data);
});
r.success(function(data) {
    alert(data); //alert it too? sure.
});​

So what's going on here? First thing is first, I needed to figure out what to do. Well to follow JQuery's pattern, I had to have an object to return from my method that had subscription methods built into it. And those subscription methods need to return a reference to their owner... so I needed to create the AsyncResult class. But, I didn't want my consumers just creating instances of that class willy-nilly, so I needed to wrap that in some closure to hide it from all but the code that I want to create new instances of it. So I wrapped the class entirely in a one-time called function that returns a reference to another function that does the work of creating the class. Now, inside the class, I did a very simple event pattern. Basically I added some arrays for each event to hold handlers for those events. Then I added some triggers (onComplete, for example) that could be called to loop through the handlers in those arrays when they were called. Lastly, I added some subscription methods that would essentially just push handlers onto those arrays. Then I was pretty much done except for adding the setTimeout trickery to kick off the passed function in an asynchronous fashion. Lastly, I added the "caller" property to AsyncResult as a nice-to-have so a consumer could get the instance of the function that was passed to the async method.

I hope that's all clear enough. I feel like I muddled my way through that explanation a little.

EDIT: I failed to mention one important thing, setTimeout will wait for any current block of code to complete before it will actually fire! So, if you have a setTimeout in a function with some huge loop that takes forever, that setTimeout, even if set to an interval of zero, will not fire until the executing code finishes, loop and all.

Calling a JavaScript function "Asynchronously"

A friend of mine asked me recently how one might execute a JavaScript function "in another thread". Well, I've got good news and I've got bad news: The good news is, I understood what he was asking and you can do that. The bad news is, JavaScript isn't multi-threaded.

Calling a function (psuedo-)asynchronously in JavaScript

To kick off a function and continue on your way without waiting for that function to return, you just need to leverage setTimeout(fn, ms).

JS

function async(fn, callback) {
    setTimeout(function() {
        fn();
        callback();
    }, 0);
}
function sync(fn) {
    fn();
}
function foo(){
    console.log('foo');
}

console.log('SYNC TEST --------------');
//synchronous
console.log('start sync');
sync(foo);
console.log('end sync');
console.log('');
console.log('ASYNC TEST --------------');
//asynchronous
console.log('start async');
async(foo, function(){ 
    console.log('async callback');
});
console.log('end async');

Output

SYNC TEST --------------
start sync
foo
end sync

ASYNC TEST --------------
start async
end async
foo
async callback

But basic JavaScript is NOT multithreaded!

JavaScript in the browser is not going to be "multi-threaded".  JavaScript will run in a single thread, but will be executed in blocks. So it will have to finish each block of code it has queued up before continuing to the next block. This is the event loop. This can cause the illusion of "multi-threading".

Monday, May 7, 2012

An Equivalent To C# params In JavaScript: Accepting Arguments And Arrays

Accepting arguments and arrays

In programming, frequently you'll come across a situation where you want to create a method or function that accepts an unspecified number of arguments. What is also common in this scenario is that you would sometimes have an array you would like to pass to said method or function. Coming from a .NET background, I would have tackled this with C#'s params keyword, but in JavaScript things are a little different.

JavaScript's arguments collection

When writing a function in JavaScript, while in the function body you have access to a collection called arguments. The arguments collection itself is not an array, it's an Arguments object. It's very similar to an array, but it's a different animal. The arguments object is simple enough though, it has a length property, and you can iterate through the arguments passed to a method by index. A good example of a function that might make use of the arguments collection is a concat function like so:

JS

function concat() {
    var s = '';
    for(var i = 0; i < arguments.length; i++) {
     s += arguments[i];   
    }
    console.log(s);
}

The function above can take any number of arguments and concatenate them together, then alert them. This works really well when we are calling it like so:

JS

concat('test',123,'foo');//test123foo
concat('blah',{}); //blah[object Object]

But when we have a bunch of data in arrays, it seems like we're SOL unless we do something hokey like use eval('') to pass the arguments:

JS

concat([1,2,3,'foo']); //1,2,3,foo ... not what we expected.

C# params keyword


In C# we had the params keyword, which allows us to pass arguments one at a time, or all together as an array. Here is an example of the same basic function as a C# method.

C#

public void Concat(params object[] args) {
   var s = new StringBuilder();
   foreach(var arg in args) {
      s.Append(arg);
   }
   Debug.WriteLine(s);
}

The method above can bee called in the following ways:

C#

//multiple arguments
Concat(1, 2, 3, 4, 5);

//or an entire array at once
var numbers = new[] { 1, 2, 3, 4, 5 };
Concat(numbers);

JavaScript's apply() method


In JavaScript there is a little known method called apply() we can leverage to pass an array to a function as arguments. The following example shows how apply() is used in this scenario:

JS

var numbers = [1,2,3,4,5];
concat.apply(window, numbers);

In the code above, you can see the apply method being called. The first argument is the scope the apply method should act in. The second argument is, of course, the array we want to pass to the function.

Other uses for JavaScript's apply() method

There are also native JavaScript methods with which we can make use of the apply method to great effect. Two that I can think of off the top of my head are Math.min and Math.max.

JS

var numbers = [1,2,3,4,5];
Math.min.apply(Math, numbers); //1
Math.max.apply(Math, numbers); //5


Saturday, May 5, 2012

JavaScript Fun Part 6: Code Golf, JavaScript Shorthand And Stupid JS Tricks!

JavaScript Is Often Code Golf

Because JavaScript is generally used on the browser, and the size of your JavaScript frequently effects load times of web pages, JavaScript code offers a fun, unique and practical opportunity to play "Code Golf" where other, compiled languages do not. What I mean by "Code Golf" is simply, trying to get code down to the fewest number of characters possible. Just like the one with the fewest strokes in golf is the winner.

Code Golf Fibonacci

Refactoring your code to make it less intensive to send over the wire can involve a bit more than simple minification. Refactoring your code to make it "smaller" is a fun task, but it commonly results in harder to read code. Here are a few examples of the classic Fibonacci sequence method where I'm using quite a bit of JavaScript shorthand to reduce the number of characters in my code.

First the plain example

// 167 characters. Not the best.
var a = 0;
var b = 0;
var next;
for (var i = 0; i < 10; i++) {
    if (b == 0) {
        b = 1;
    }
    console.log(b);
    next = a + b;
    a = b;
    b = next;
}​

Now for code golf!

//74 characters!​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var r=[];for(var i=0;i<10;i++){console.log(r[i]=(r[i-1]||1)+(r[i-2]||0));}
//67 characters
var i=0,p=0,c=0,n;while(i++<10){console.log(((n=p+c||1,p=c),c=n));}
//Old winner: 64 characters
for(var n=1,i=0,p=0,c=1;i<10;n=p+c,p=c,c=n,i++){console.log(n);}
//New winner: 51 characters (still keeping the var, so + or - 4 chars):
for(var i=0,p=0,c=1;i<10 data-blogger-escaped-c="p+c),i++);" data-blogger-escaped-console.log="" data-blogger-escaped-p="" data-blogger-escaped-pre="">


JavaScript Shorthand

JavaScript actually has a number of shorthand methods for doing common (and uncommon) tasks that can help immensely when you are trying to limit the number of characters in what your doing.
var o = {}       //object literal
var a = []       //new array
var r = /.*/     //new regex
var s = ''+0;    //convert to string
var n = +'7';    //convert to number (7)
var b = !!'';    //converts to a boolean
var f = ~~3.434; //same as Math.floor(3.434)
var g = -~3.434; //same as Math.ceil(3.434)
var x = 5e3;     //same as 5000
var c = c || z;  //coalesce, if c is null then set it to z.
'abcde'[1];      //charAt shorthand, results in 'b'.
+new Date();     //shorthand for (new Date()).getTime();
var a = x?y:z;   //ternary operator, short for: var a;if(x){a=y;}else{a=z;}
!0               //shorthand for true (actually boolean)
!1               //shorthand for false (also boolean)
if(x){}          //if x is not false, null, undefined, '' or 0.

Weird JavaScript "Encoded" Strings!

alert((''+{}._)[5]+' '+(''+{}.$)[0]+(''+!0)[1]+(''+{}._)[5]+(''+{}[$])[6]+(''+!1)[1]+(''+{})[6]+(''+!0)[3]+(''+{}.$)[2]);

So what's going on here?

What this is doing is leveraging the shorthand above for silly purposes. You'll notice, when you break it down, what it's doing is concatinating a bunch of string fragments together that where retreived by converting things like [object Object] and "undefined" to strings with the ''+ conversion technique. The fragments were retrieved by index with the "abc"[0] technique mentioned above. It's pure silliness, obviously, but it's a good example of how crazy you can get with these shorthand techniques. Even if, in this case, the shorthand techniques aren't shorting anything, they're just meant to make the code look confusing.

Friday, May 4, 2012

JavaScript Fun Part 5: Build Your Own Custom Events

Custom Events And JavaScript

A few times in my life I've been asked "How do I make my own events in JavaScript?". Generally I tell them to just use JQuery or any number of libraries that have already solved this problem. But for sake of argument, let's say you wanted to implement something like this yourself. The problem at hand is JavaScript doesn't have anything OOTB that handles event binding and triggering. DOM does, of course, but DOM isn't JavaScript (it's just that slow P.O.S. that JavaScript is usually manipulating).

So how do we go about implementing a rudimentary JavaScript event library that will enable us to bind to our own custom events and trigger them? First, we'll want to set up the "guts" of this functionality with two methods: A bind method and a trigger method.

/* Create a namespace for us to work in
* because I'm lazy, I'll call it "E" */
var E = E || {};

/* Our bind method: this accepts a target, which is
* the object we're going to attach our event to, an eventname,
* which serves as a key for the events we put on the class, and
* of course, the handler, which is the function that will be 
* called when the event is triggered. */
E.bind = function(target, eventname, handler) {
    if (!target.customevents) {
        target.customevents = {};
    }
    if (!target.customevents[eventname]) {
        target.customevents[eventname] = [];
    }
    target.customevents[eventname].push(handler);
};
/* The trigger method: this accepts a target, which is the
* object containing the event to be triggered, the eventname,
* which is the key for the collection of handlers to be 
* called, and args, which are the arguments to pass
* to the handlers. */
E.trigger = function(target, eventname, args) {
    if (target.customevents && target.customevents[eventname]) {
        var handlers = target.customevents[eventname];
        for (var i = 0; i < handlers.length; i++) {
            var handler = handlers[i];
            handler.apply(handler, args);
        }
    }
}

//create an object to bind events to.
var myObject = {};

//bind a couple of handlers to the "testevent".
E.bind(myObject, 'testevent', function(a, b) {
   alert('called! ' + a + ', ' + b); 
});

E.bind(myObject, 'testevent', function(a, b) {
   alert('Say what? ' + a + ', ' + b); 
});

//trigger the "testevent".
E.trigger(myObject, 'testevent', ['FOO', 'BAR']);
//called! FOO, BAR
//Say what? FOO, BAR

What's going on above is pretty simple. Basically, our bind method takes a function reference and puts it in a collection of arrays keyed by the eventname (in our test case, "testevent"). Then our trigger method, when called, gets all of the handler function references on the object keyed by the event name ("testevent" again), and calls them. There's a little trickery in there with the JavaScript apply() method. Basically, apply(scope, arr) is just a way of passing an array of values as arguments to a function within a specified scope. The scope in this case is mostly irrelevant.

So how do we make this prettier? I don't like magic strings!

Okay so let's use our E namespace in a way that is a little cleaner, something like how JQuery uses events, perhaps?

/* create a class with a method to call that will
* trigger a custom event, and a method to use to bind 
* the that custom event. It's a static class 
* because, again, I'm lazy. */
var Foo = {
    bar: function(a, b) {
        E.trigger(this, 'bar', [a, b]);
    },
    onBar: function(handler) {
        E.bind(this, 'bar', function(a, b) {
            handler(a, b);
        });
    }
};

Now we use our prettier methods in whatever code consumes this class.
// bind to the event.
Foo.onBar(function(a, b) {
   alert('Foo.bar called! ' + a + ', ' + b); 
});

// call bar() and trigger the event!
Foo.bar('TEST', 'MONKEY');

That's really all there is to it. Of course, as I said above, there really isn't a good reason you should be implementing your own custom event library, when there are already so many powerful and refined libraries out there that tackle this problem, such as JQuery.

Thursday, May 3, 2012

JavaScript Fun Part 4: The Singleton Pattern

What Is The Singleton Pattern?

This is a pattern by which you allow one and only one instance of an instanced object to be created for use. Generally, this object is created in a "lazy" fashion. That is to say, there is no instance created until it's requested the first time. Examples of where this pattern would be used on the client are few and far between, I suppose, but with the advent of JavaScript server technologies like NodeJS, I'm sure that the JavaScript singleton pattern will start to find a lot more use.

Implementing The Singleton Pattern In JavaScript

I have seen a few ways this pattern has been implemented in JavaScript. All of them work pretty much the same way with a containing function called immediately, so as to allow a private "instance" of the class in question. The following is my favorite way to implement this pattern:


var getSingleton = (function() {
    //this will hold our one instance.
    var instance = null;

    //here is the class declaration, all private n stuff.
    var Singleton = function() {
        this.foo = function() { 
            alert('Singleton.foo() called.');
        };
    };

    //we return a function to create and get the one instance.
    return function() {
        //create the one instance if necessary.
       instance = instance || new Singleton();
       return instance;
    };
})();

var x1 = getSingleton();
var x2 = getSingleton();
alert(x1 === x2); //true

try {
    var fail = new Singleton();
}catch(err) {
    alert(err); //Reference Error: Singleton is not defined.
}
​

I start off by creating the containing function that executes immediately and returns its result to the getSingleton variable. The containing function as a private variable for storing our singleton instance, as well as a private declaration for our function class, Singleton. Because Singleton is declared inside the closure of our containing function, it can't be accessed anywhere else. Now we move in for the kill: Our containing function returns a function reference that does the following: Checks to see if our instance is null, populates it with a new instance of our Singleton class if so, then returns the instance. Now getSingleton has a function reference in it that will get our one instance of the Singleton class, creating it only if necessary.

EDIT: Another approach! 

I just wanted to show another approach for a Singleton class that has the advantage of one less closure. In fact, I think I prefer this method to the other. More closures means more memory usage (however small), so I think going forward this will be my most likely singleton implementation.

var getSingleton2 = (function() {
    //this will hold our instance.
    var instance = null;

    //private methods to the singleton go here.
    var privateMethod = function() {
        alert('private');
    }
    //return a method that gets the instance.
    return function() {
        instance = instance || {
            //declare public members here.
            foo: function() {
                privateMethod();
            }
        };
    };
})();

var s1 = getSingleton2();
var s2 = getSingleton2();
alert(s1 === s2);​ //true​​​​

Wednesday, May 2, 2012

Marvel's Security Makes Nick Fury Cry

I'm going to take a break from my JavaScript series for a minute because I need to vent my geek rage about something that just happened to me. I was logging into Marvel's website and I had forgotten my password. So like any other user, I requested my password be resent to my email address. The typical form was filled out and I went to my inbox and read a few emails while I waited.

When the email arrived I was horrified! The email contained my actual password! That means that Marvel was storing my password on their end! The horror! Now I'll admit that I use a different password for every site I log into (I'm not joking). I actually use a pass phrase, when I can. So I'm sure if their database was compromised I'd have been safe. But, storing passwords is an incredibly bad idea. Even if they're encrypted. If the hacker has compromised your network, they'll likely find your encryption keys too.

There are already volumes written about why storing passwords is bad. There are tons of stories of passwords stolen. And there are lots and lots of articles on what you should do to authenticate users with a password and how you should be storing password hashes.

I just wanted to vent my geek rage and link a few key articles for anyone that reads this to read and ponder, most of them by Jeff Atwood, who seems to have a hot button for this issue.

More from Mr. Atwood on the matter:


(Image copyright Marvel)

JavaScript Fun Part 3: Implementing A Static Class

What Do I Mean "Static Class"?

First off, a lot of my programming lexicon will be coming from a Microsoft .Net perspective, and to be quite frank, even that has evolved a lot along the way, due to the fact I am self-taught. When I say "static class" what I'm talking about is a class whose public members are accessible without creating an instance of that class.

What Is A "Non-Static Class" In JavaScript?

A instanced (non-static) class in JavaScript is the classic JavaScript function class. Created by declaring a function, then calling it along with the "new" keyword:

var Foo = function () {
   this.bar = function() {
      alert('Foo.bar() called.');
   };
};

var f = new Foo();
f.bar(); //Foo.bar() called.;

Implementing A Static Class In JavaScript

In JavaScript, a static class isn't much more than an object literal. Because objects in JavaScript are dynamic, we can augment them outside of the declaration to our hearts content, but the nature of the beast is the same: It's an object with a bunch of properties and methods on it.


var FooStatic = {
   bar: function () {
      alert('FooStatic.bar() called.');
   }
};

FooStatic.bar(); //FooStatic.bar() called.

Implementing a Static Class With Private Members

The first thing many people will notice about this pattern is the lack of privacy of it's members. No members declared on FooStatic in the manner will ever be hidden from other code. But Closure, being awesome, gives us a clever way around that:

var FooStatic = (function() {
    var barPrivate = function() {
        alert('FooStatic.barPrivate() called.');
    };
    return {
        bar: function () {
           barPrivate();
        }
    }
})();

FooStatic.bar(); //FooStatic.barPrivate() called.

What the... ?

So how did this work? Using the magic of Closure, we created a container function that contained the private member we needed, in this case the variable holding the function reference to "barPrivate", then we had that container function return an object literal that had the method "bar" on it that makes a call to "barPrivate", which it has access to because it's in the same closure. We then immediately call that container function, putting its result in FooStatic. Easy peasy, if a little tricky.

This is just one of many fun uses of Closure, which I've learned to be the keys to the kingdom when it comes to JavaScript's full potential.

Tuesday, May 1, 2012

JavaScript Fun Part 2: Closure

What is closure?

Closure is basically leveraging variable scoping in JavaScript to privatize functions and variables used within another function. In other words, a function that creates another function and returns it. But understanding the scope of your variables in JavaScript, and how you can use that scoping, makes JavaScript a much more powerful tool.

A Small Example Of Closure

var globalVar = 'something'; //available everywhere.

//a class foo (available everywhere)
var foo = function () {
   // a method only available inside our class.
   var privateMethod = function (a) {
      alert(a);
   };

   // returning a function creates a closure,
   // enclosing all of the private variables and
   // functions inside of the returned function reference.
   return function (b) { 
      // a variable only available inside this function.
      var prefix = 'OMG: ';
      //alert 'OMG: b'.
      privateMethod(b); 
   };
};

var closureFoo = foo(); 

//should alert "OMG: HI WORLD!"
closureFoo('HI WORLD!');

As you can see in the example above, using closure, you can hide a function of variable from some outer scope that is being used by another function. Generally, I would use something like this in more of a command pattern sort of way. Where I need to create some complicated command I needed to execute over and over again, or that may even need to maintain state on itself.