Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Entries Tagged as 'Misc Toolkits'

Underscore.js: jQuery without the DOM

Posted by Dave Mahon

DocumentCloud bills Underscore as “the tie to go along with jQuery’s tux,” but I think that this description is misleading.

In less than 4KB, and without manipulating object prototypes, it provides a superset of jQuery’s set manipulation, fills the gaps in IE’s implementation of arrays, types variables correctly and provides several other neat tricks.

Neat tricks, you say? How about automatically changing the value of this when you call a function? Or providing a very simple templating engine? Or elegantly handling variable name conflicts? Those would be the bind(), template() and noConflict() methods, respectively.

To top it all off, it uses native methods, in browsers that support it, and offers both object-oriented and functional coding support.

With no dependencies, a tiny footprint, and a huge punch, it’s a powerful tool at your disposal.

Accounting.js A handy formatting library for numbers and finance

Posted by Don Albrecht

Today I stumbled across a handy little javascript framework called accounting.js.  Like the handy date.js library.  It focuses ongoing one thing extremely well. Convert numbers between simple strings of digits into nicely formatted easily readable strings.

it has just a few functions.

formatMoney()

by default, format the string to USD with 2 decimal places, comma separation at the thousands and a $ sign.  Optional params of [currencySymbol], [precision], [thousands separator], [decimal separator].

formatColumn()

just like formatMoney, but it takes an array of values and white space pads their conversions to the same length.

unformat(string)

parse a given number formatted string and return its numerical value.

Joss Crowcroft’s Original Blog Announcment is here:

http://www.josscrowcroft.com/2011/code/my-weekend-project-accounting-js/

And the GitHub site is here:

https://github.com/josscrowcroft/accounting.js

Using functions to further improve mustache

Posted by Dave Mahon

When we last discussed mustache, we saw data that looked like this:

{
  "title": "Our Web Store",
  "items": [
    {"name": "Widget",
     "unitprice": "1.45",
     "quantity": "2",
     "totalprice": "2.90"
    },
    {"name": "Whosit & Whatsit",
     "unitprice": "0.45",
     "quantity": "1",
     "totalprice": "0.90"
    }
  ]
}

There are obvious issues though. We have leading and trailing zeros and we have totals that are obviously calculated. These are all display issues, so why do we tolerate having display data in what functions as our model?

Never fear, for you can use functions in the data, as you would expect from any JSON source. Let’s look at that in action.

First, we’ll restructure our data a bit:

{
  "title": "Our Web Store",
  "items": [
    {"name": "Whosit & Whatsit",
     "prices": {
       "unit": "0.45",
       "total": "0.9"
     }
  ]
}

Now we’ll introduce the functions, taking advantage of Accounting.js as well.

{
  "title": "Our Web Store",
  "items": [
    {"name": "Whosit & Whatsit",
     "prices": {
       "unit": "0.45",
       "total": "0.9"
     },
     "quantity": "2",
     "unitprice": function() {
       return accounting.formatMoney(parseInt(this.prices.unit, 10));
     },
     "totalprice": function() {
       return accounting.formatMoney(parseInt(this.prices.unit, 10) *
              parseInt(this.quantity, 10));
     }
  ]
}

We’ll get almost the same output as before (with an extra dollar sign which we can easily remove from the template) but now we’ve moved all of the display processing into our display layer, which is pretty nice.

Templatize your dynamic site with mustache

Posted by Dave Mahon

Let’s face it. We spend a lot of time writing markup in all sorts of languages. Whether we’re producing the next big social networking site or creating a funky template, there is a lot of boilerplate that is continuously repeated. More importantly, chances are we’re implementing it in a mix of JavaScript, HTML and our backend language of choice.

It makes managing our presentation a muddled mess. That’s where template engines come in. If you’re using pure PHP, you could use Smarty, but this is a JavaScript-focused blog and you probably have some of your presentation in pure JavaScript anyway.

That’s where mustache comes in. Available in most web languages, it provides a simple and flexible way of integrating content into your site.

Let’s say we’re implementing a receipt purely in JavaScript. Our data looks like this:

{
  "title": "Our Web Store",
  "items": [
    {"name": "Widget",
     "unitprice": "1.45",
     "quantity": "2",
     "totalprice": "2.90"
    },
    {"name": "Whosit & Whatsit",
     "unitprice": "0.45",
     "quantity": "1",
     "totalprice": "0.90"
    }
  ]
}

First, we’ll integrate the mustache library, like so:

<script type="text/javascript" src="mustache.js"></script>

Next, we’ll define the template:

var template = "<h1>{{title}}</h1>

{{#items}}
    <dt<strong>{{name}}</strong></dt>
    <dd>${{totalprice}}</dd>
    <dt>{{quantity}} @ {{unitprice}}</dt><dd></dd>
{{/items}}";

Finally, we simply have to render the HTML, like so:

var html = Mustache.to_html(template, json);

This will produce output like:

<h1>Our Web Store</h1>
<dt><strong>Widget</strong></dt>
<dd>$2.90</dd>
<dt>2 @ 1.45</dt><dd></dd>
<dt><strong>Whosit &amp; Whatsit</strong></dt>
<dd>$0.90</dd>
<dt>1 @ 0.45</dt><dd></dd>

You can then use your DOM manipulation technique of choice to insert the markup.

Note that it automatically escaped the ampersand. Had we used three curly brackets, then it would have allowed it to remain literal.

What happens when we items is an empty array or, worse, isn’t there at all? It simply doesn’t appear, because the hash prefix in our template makes it conditional. You can invert the condition (say, for presenting a special message for missing information) by using a caret (^).

Since the items element was actually an array, mustache also automatically knew to loop through, which could potentially be handy for commenting systems.

Date.js My New Favorite Javascript Date Library

Posted by Don Albrecht

Earlier this week, I discovered that Safari doesn’t support dates in ISO 8601 UTC combined format:  “2010-06-19T03:11Z”.  This was a problem as my production system was delivering me a json file with dates in this format and my project was simply a new UI for the existing server.  A quick round of googling found DateJS a powerful chainable Date extension that enables both unified parsing and mask based date rendering.  I’d only played with it for a few minutes before I was completely hooked on it.  Just look at what it can do.

   1: // What date is next thursday?

   2: Date.today().next().thursday();

   3:  

   4: // Add 3 days to Today

   5: Date.today().add(3).days();

   6:  

   7: // Is today Friday?

   8: Date.today().is().friday();

   9:  

  10: // Number fun

  11: (3).days().ago();

  12:  

  13: // 6 months from now

  14: var n = 6;

  15: n.months().fromNow();

  16:  

  17: // Set to 8:30 AM on the 15th day of the month

  18: Date.today().set({ day: 15, hour: 8, minute: 30 });

  19:  

  20: // Convert text into Date

  21: Date.parse('today');

  22: Date.parse('t + 5 d'); // today + 5 days

  23: Date.parse('next thursday');

  24: Date.parse('February 20th 1973');

  25: Date.parse('Thu, 1 July 2004 22:30:00');

And Yes It supports ISO 8601 UTC combined format!.

A quick replacement of my existing date toolkit in the project and my bugs were fixed.

Simile Timeline, An Advanced Timeline VIsualization

Posted by Don Albrecht

As Timelines go, this is probably the most advanced widget I’ve come across.  It’s designed to facilitate theming, huge time ranges, various levels of detail, large variations in resolution and even data mashups.

Simile Timeline

So, how does it work?

Reading through the project wiki, they call out the way individual lanes of the timeline are built in code.  It’s a well formed architecture so I thought I’d call it out as well.

  • The timeline is divided into bands.  Each band has its own data source (‘event source’) which allows for handy data mashups.
  • The band has its own ether, a map between pixel coordinates and dates / times.
  • The ether has a dedicated ether painter which is responsible for date / time rendering as well as background details and highlighting.
  • Decorators augment the background of the band
  • the bands event painter is owned by the band and responsible for the rendering of a bands events.

Check it out here:
http://www.simile-widgets.org/timeline/

You can also  read more about the architecture here:
http://code.google.com/p/simile-widgets/wiki/Timeline_Basics

 

Expand your debugging aresnal with pi.debugger

Posted by Don Albrecht

pi.debugger is a new debug console that acts as a graceful counterpart to firebug.  I’ve  and Firebug is an awesome tool for debugging, hands down.  Unfortunately, it is Firefox specific and has to be installed on the clients machine.

Firebug lite is great, but it is extremely limited and provides little more than a logging console.  pi.debugger sits somewhere in between.  It’s not as full featured as firebug, but it does provide the ever useful evaluation console as well as a DOM browser.

Check it out here:

http://code.google.com/p/pi-js/

And test drive it here:

http://kodfabrik.com/app/pi.debugger/

DamnIT Remote Javscript Error Reporting

Posted by Don Albrecht

Firebug and its kin are awesome for debugging javascript, but once our scripts are in the wild we really don’t have any feedback of any kind about the state of the browser.  DamnIT from JupiterIT attempts to alleviate this by providing an automated feedback system for javascript applications.

How it works:

  1. A box appears prompting you to describe your most recent actions:
  2. One of the following occurs:
    • you type something and click send
    • you click “close”
    • 10 seconds pass with you doing nothing
  3. DamnIT emails you the following information:
    • Browser
    • Page
    • HTML Content
    • Description (if you entered one)
    • Error message
    • File name, line number, and stack (if the browser supports them)

On the surface this is an incredible system.  In practice there are a few key issues that I think need addressed before the product is an ideal fit for every situation.  Basically, I have severe reservations about the email only nature of the system and its dependence on central management.  Both of these are key issues when dealing with sensitive information or large volumes of error messages and I’m sure will be addressed with future versions.  I am going to integrate the system into the next release of BLT and will be providing feedback from those efforts in the near future.  In the short term, you can check out DamnIT here:

https://damnit.jupiterit.com 

Helma, Server Side Javascript

Posted by Don Albrecht

Helma Logo Helma is an impressive server side environment for deploying javascript based applications.  Currently in version 1.6 it presents a powerful and useful way to construct web applications.

Key features:

  • Applications: Helma can serve multiple independent applications, each existing with its own global scope & code repository
  • Static Files: Helma can serve static files independently of applications.
  • Controller / Event Driven model
  • Powerful templating system
  • Hybrid Client / Server Object Model
  • Objects mapped to RDMS or stored in persistent XML object layer
  • Access to any Java package via addition of JAR to Classpath.

Although I haven’t played with it much yet, I’m excited to explore Helma as a way to build comprehensive web applications while focusing on my language of choice: Javascript.

Check out Helma at:

http://helma.org/ 

!! You’re True (or False)

Posted by Don Albrecht

Ok, so you probably know that Javascript like most other programming languages treats “0″ as false and any other numerical value as true in logic statements. Usually, this is sufficient, unfortunately, sometimes, you need a bit more consistent behavior. For example, ( 2 && 3 && true ) = 2.

Luckily there is a simple fix. Since, ! only operates on boolean data. !(0) is true and !( any other non-null value is false). Therefore, !! returns the boolean value of the original expression.

Another way of coding it, would be “Boolean ( expression );” and directly casting the expression to a Boolean. All things being equal, this would honestly be my preferred way of doing it. After all, legibility in code is one of the utmost considerations for most development, but since bandwidth is also a major consideration in javascript and !! is reasonably intuitive, I personally use it wherever necessary.