Posts Tagged ‘javascript’


Lately I’ve been working on a client/server side validation library. I had a need to chain a bunch of methods together, and what that meant was a need to modify how the original functions were called without changing them. This lead to a need to pass some variables into a function and still wait to accept more parameters later. I already knew about currying, which I will summarize as being able to pass as many variables as you feel into a function. A couple other techniques were needed to solve this.

First I learned about the apply and call functions (I know I am late to the party…). In this case apply was extremely helpful, it let me set a context (change the value of this) and collect some parameters together and pass them into a function.

Next I discovered partial applications. This is more of a technique than anything else. In iz we have the following source code:

function validator_partial(fn) {
    //get all arguments except the first, which is the function name
    var args =, 1);
    //pass the "value" in as the first parameter so that the user of this library doesn't need to
    //return a new function
    return function() {
        //combine all arguments made to this function with the ones above
        var allArguments = args.concat(,
        //get the result
        result = validators[fn].apply(null, allArguments);
        //update this object
        if (!result) {
            if (typeof this.error_messages[fn] !== "undefined") {
            } else {
            this.valid = false;
        //return "this" to allow for chaining of methods
        return this;

for (var fn in validators) {
    //for each function, call the partial and pass in the function
    if (validators.hasOwnProperty(fn)) {
        Iz.prototype[fn] = validator_partial(fn);

At the bottom I am grabbing the validators, and assigning them to the prototype of the Iz object. Before the validators get called though they go through a partial. This partial is a function that returns a function. The closure allows you to house some variables within it. When the returned function gets called it has access to the outer one’s scope, which is how you are able to pass in parameters before and after the function is called. On top of that this system lets you pass in as many params as you need and it simply forwards everything on.

With this method I was able to replace all of the first parameters (the ‘values’ with the value from the Iz object. This means less typing, which is always nice!

There are 2 problems with creating classes in JavaScript. 1) if you create classes in separate files you may need some system to tie the files up together for speed purposes. 2) typically your might lose your function names while you debug if you aren’t careful. In other words, you might be seeing tons of anonymous functions when you debug. There is a balancing act that goes on here.
How to define a class and methods typically:
Method 1:
function MyClass() {
MyClass.prototype.myfunc = function(){
Method 2:
function MyClass() {
   this.myfunc = function(){
Method 3:
var MyClass = {
   myfunc : function() {
In all 3 of these techniques you lose the name of the function in the debugger. Why? Well because your functions are technically anonymous.
function() {}
function bob(){}
So how can we make this happen? Well… how about this:
MyClass.prototype.myfunc = function myfunc(){}
Yea, that actually won’t work everywhere unfortunately, but this will:
function MyClass{
   function MyClass_myFunc(){
   this.myFunc = MyClass_myFunc;
It is a bit repetitive, but this will help you find where issues are occurring in a debugger. You debugger will now state the issue came from MyClass_myFunc() instead of (?). I believe some modern browsers do actually convert the (?) to the right function, but I believe it stops at some point in the call stack. So this is great!
Well you might also wonder how to namespace? What is a namespace in javascript anyways? Well a namespace like anything other than a “primitive” in javascript is an Object. It is defined:
var mynamespace = mynamespace || {};
This will either define a namespace named “mynamespace” as a new object literal OR it will use the existing mynamespace object in the current scope. So to add a class to our namespace we would just add our class to it:
function MyClass{
   function MyClass_myFunc(){}
   this.myFunc = MyClass_myFunc;
   mynamespace.MyClass = MyClass;
The problem with this is that we have both: MyClass the global defined and mynamespace.MyClass. To prevent this from occurring we wrap everything up like this:
var mynamespace = mynamespace || {};
(function() {
   function MyClass{
      function MyClass_myFunc(){
      this.myFunc = MyClass_myFunc;</span></div>
      mynamespace.MyClass = MyClass;
Using the power of closures we have limited our globals to 1. We ONLY have mynamespace exposed globally. Nowwwww, we got 1 other thought that we should think about. What happens if our class depends on other classes? I’ve been looking at a good way to mimic Node.JS’s commonjs library client side. I think require.js will work well for this. How we might want to define our files with require.js:
var mynamespace = mynamespace || {};
require(["jquery"], function($) {
   function MyClass{
      function MyClass_myFunc(){
      this.myFunc = MyClass_myFunc;
      mynamespace.MyClass = MyClass;
Maybe? I think this looks good. It mimics the functionality we had earlier by limiting our global usage. You might be wondering what require is doing. Well, basically it is acting like a map. You specify where jquery is located and if it isn’t include it will get included. You can do this with all your classes in the file defined by require. Note, that this does to some degree break from our notion of joining files together to optimize a website. While I am still investigating this, it seems that once a dependency is loaded requirejs will not load it again. This means that require might actually test for the existence of the dependency and if it isn’t around THEN load that file. This should allow you to use require’s optimizer to pull in various portions of a project at load then the rest later. Still reading, but this seems like the most optimal setup! 🙂
By the way, using backbone.js also forces you to adhere to the above conventions!

Hi All,

If you haven’t seen this awesome menu system check it out:

Or check out the how-to here:

I really thought this menu system was cool and with a few tweaks can function as integral part of the user experience on a website. Recently I had decided to leave the fabulous world of Prototype/Scriptaculous and move to JQuery. Mostly because it seems the industry has standardized around JQuery. It had some what of a learning curve, but it took about a day to really make the switch. Having to convert this sideBar script really helped with that process.

As a final note before I post the code. The animations aren’t exactly the same, but with JQuery you can create your own custom animations so feel free to modify as you wish. Changes are below!


var isExtended = 0;

$("#sideBarContents").animate({ "width":"toggle"},{duration:2000,queue:false}

$('#sideBarTab').html($('#sideBarTab').html().replace(/(\.[^.]+)$/, '-active$1'));
$('#sideBarTab').html($('#sideBarTab').html().replace(/-active(\.[^.]+)$/, '$1'));

So thats cool… In my script I also wanted somewhat accordion style items expanding within my sidebar so I use the following line of JS to dynamically add items into the sidebar (well sort of, without giving too much away).

$("#divIdToAppenedTo").append("<li><a class='header' href='#' onclick='$(\"#"+slug(name)+"\").animate({\"height\":\"toggle\"},{duration:1000,queue:false});'><div style='margin:10px 0 0 15px;'>"+name+"</div></a><div id='"+slug(name)+"' style='display: none; padding-left:15px;'>");

Woo enjoy!

Update: someone requested (via comment) the css for this. Please note you will need to modify width, colors, backgrounds, etc… I stripped down a ton of visuals in order to not release proprietary content: sb-package


UPDATED: Nov 11th, 09 , changes: added python info

I have been struggling to find a way to get around selenium’s onload deficiencies. I tried all sorts of ways to hack up my script, but alas it mostly ended up in turmoil. Onload is one of the main ways most developers use to make sure certain actions happen in code, and my entire content bed was about go into flames before I found the light at the end of the tunnel. A magical gift from the heavens known as AutoIt saved me from a timely demise…

All retardedness aside… (sarcasm)..

AutoIt really did solve this problem for me. It may not work so well for others.. it depends on your situation. For me a simply wanted to close a popup window after it loaded from a different windows onload and then click the popup’s confirmation’s Ok button. Then close the original window that started all the madness…

The cool thing about running the code below is that it just runs as a daemon of sorts in the background waiting for some unruley popup to be struck down with Wrath of Kahn, plus it can also test for popups with different names. I am hoping I can do some sweet regex stuff, otherwise, life may prove difficult. In any case here is my AutoIt script:

While True
   If WinWait('Name of the final Popup', '', 1) == 1 Then
     ;Wait for page to load if found
     ;Close Page
     ;Confirm Dialog
     ;Close Lanucher Page
   ;Let another thread have a turn

Now, lets say you want the above to be directly embedded into your script rather than have it constantly running externally. I personally use python for my Selenium scripting so in python you can do the follwoing (which is the equivalent of the above script).

from selenium import selenium
import unittest, re, time
from datetime import date, datetime
from xml.dom import minidom
from win32com.client import Dispatch

# Auto it window closing stuff
def autoItCloseWindows(self):
   auto = Dispatch("AutoItX3.Control")
   #Your Popup Name Here is the name of the window...
   #I did this because different windows could open for my project
   if (auto.WinWait("Your Popup Name Here", "", 1) == 1):
      # chill
      # close window
      # wait
      # confirm dialog box
      # close the launcher window

To run this script you mainly need selenium, time, autoit3 and win32 dispatch. To download win32 stuff for python click here. Another thing to note is that this will only work for windows. There are similar solutions available for *nix. If you are using a mac to do things like this it is probably a waste of your mac ha, but there are also similar solutions.

Good luck oh weary travelers…