Archive for the ‘JavaScript’ Category

Taking out node.js for a spin with Bomber

Saturday, January 2nd, 2010

The node.js project has been getting a lot of good press and positive attention over the past few months. With good reason. If this is the first you’re hearing of node.js, it’s officially an “evented I/O for V8 JavaScript” but more generally it is used as a tool for writing non-blocking network servers. This means that it can easily be made into a JavaScript-based and highly efficient web server. If you’re curious, have a look at Simon Willison’s nice write-up.

Node is still in it’s infancy. For example, there’s is still a lot of discussion going on on the mailing list about core API (i.e. how to handle communication between and chaining of events or even how the final file API is going to look). Since node isn’t designed explicitly as a web server, there’s only low-level http support — and of course, there is no standard web application framework for handlings requests, sessions, cookies, and users.

The first question to be answered is if you’d actually want big web applications to run solely on node.js? But for now I’ve skipped that question entirely and simply asked how I’d approach writing such and application (hopefully reusing some of the code being currently being pushed by the node community)?

It seems as if every person in that community has written her or his own lightweight library for handling web requests. To name a few, there’s Djangode, Express, Coltrane, Vroom, and node-router). A lot of these are obviously inspired by the approaches taken by either Django or by Rails (it’s right there in the names), but taken as a whole they’re very limited in how they approach the task. Most of the frameworks are just different syntaxes for binding a JavaScript function() {} to a URL — without the modular approach taken by their more mature counterparts.

This means that you can easily use any of these frameworks if you need to write up a simple — and fast! — web app in a single file with a few hundred lines of code (in that case, I’d opt for Djangode), but you’d be stomped if wanted different, re-usable applications meshing into a single project. Benjamin Thomas has gone in designing mode in order to come up with a mini-framework which isn’t quite as mini as the ones listed above. His ambition is to build…

- The ability to bundle up a collection of controllers/views, models and templates into “apps” for easy portability and reuse.
- Smart defaults that hide a lot of the options/power/complexity. I think this is important for getting up and running quickly.
- A code base that is as small and simple as possible.
- I want it to feel javascript-like. Whatever that means.

The end result is Bomber. I like how Bomber creates simple URL routing to file-based (or rather node.js module-based) views, and how it lightly extends the core http.ServerRequest and http.ServerResponse objects. It feels almost native, but you see that enough of a foundation exists for this framework to actually include the ability to handle POSTs, sessions, cookies, multiple applications within a project and so on. There are no great ambitions where the framework will suddenly include a native XML parser (just a random example, sorry), but there’s enough room to grow and spread the webby wings a bit.

The Bomber project is very much in flux. In fact, it might even be dead since the last commit is a month old. And the entire project is build around an Action API which about to be deprecated. Hopefully to be replaced with DOJO-style, native Deferreds.

I’ve been playing around a bit by adding some extra stuff to Bomber through my own fork at github. I’ve already tweaked a little with the app structure to allow for multiple projects to be bootstrapped with different configurations from the same Bomber library, and there is some copy-paste and bug fixes in there as well. This will likely include experiments with multi-application projects, per-application media directories, cookie and session handling and templating (although I disagree with Benjamin that Bomber should include its own templating system; this could probably be left for the programmer to choose).

And now, back to Jersey Shore, bitches!

Could Gears be the trojan horse for Chromium?

Thursday, September 4th, 2008

Wouldn’t it be nice if Google Gears included the entire Chromium rendering engine?

A few people have been posing the idea of using Flash’s own WebKit-powered browser to render web pages in Internet Explorer, which would achieve the duplicate goal of leap-frogging the web platform forwards and not forcing users to upgrade their browsers. (Such an approach would be a hack at best, and it would introduce other problems.) In a similar vein, we’ve seen people build plug-ins for IE from pieces for Mozilla to upgrade the Explorer’s capabilities.

Up to a few days ago, Google’s approach to this problem was to distribute light platform upgrades (such as offline browsing and location awareness) to existing browsers in their Google Gears plug-in. With the release of Google Chrome this strategy has shifted: Rather than upgrading the existing platform, Google is making a play to replace the platform. Presumably Gears is going to co-exist with Chrome. We’ll see development on Gears as long as support in Google’s products for IE, Firefox and Safari is needed. Which is going to be a long, long time.

Now, here Google presented with an appealing opportunity. In addition to just embedding Gear in Chrome they could embed Chrome in Gears. This would allow developers to require Gears in Internet Explorer (IE, of course, being just a random example) and then use Chromium to render pages rather than IE’s own native engine. Intriguing, right?

FeatureSlider [script]

Saturday, March 22nd, 2008

» Instant Gratification Now!

If you’ve ever visited the front page of Beanstalk you’ll know that they have a very nice inline feature tour, which scrolls your across some html content on the front page.

In a project I’ve been working on we need a similar way to browse through a series of articles, so I’ve built a very simple Prototype (and optionally Scriptaculous, if you want the animation to work) script, which makes it trivial to include such tours: feature-slider.js

For the guys at Beanstalk, if you’re reading this: To get your tour to work correctly in Internet Explorer, simply add position:relative to the overall container. I like your temporary IE hack, but still…

Using the code

To use the code, simply do this:

<style>
  #slide {width:300px; height:200px; overflow:hidden;}
</style>
<script src="feature-slider.js"></script>
<div id="slider">
  <div>First item</div>
  <div>(...)</div>
  <div>(...)</div>
  <div>Last item</div>
</div>
<script>var fs = new Slider('slider');</script>

A few real-life examples:

I’ve tried to keep everything simple, which means that the script doesn’t try to build navigation for you. Usually, this is where other similar carousel scripts go wrong. Instead you can use a few functions to browse the items in the FeatureSlider, or you can use callbacks to build advanced navigation:

fs.go(n): Go to a given item in the FeatureSlider
fs.next(n): Go to next item
fs.previous(n): Go to previous item
fs.first(n): Go to first item
fs.last(n): Go to last item

Initiating the code with the events arguments allows you to receive callbacks onLoad and onChange:
var fs = new FeatureSlider($('slider'), {
  onLoad:function(obj){
    alert('Loaded ' + obj.items.length + ' items');
  },
  onChange:function(obj, index){
    alert('Showing ' + index + ' of ' + obj.items.length);
  }
});

Panning/Zooming/Browsing within a photo [script]

Sunday, March 16th, 2008

So I’m doing this great new product for 23 and I’ve built some simple code which allows you to navigate large images in a way quite similar to Google Maps. This is what it looks like (best in non-IE browsers for now):

You can navigate the photo like this…
 Zoom In: Double-click
 Zoom Out: Alt+Double-click
 Navigate: Drag photo

Using the code

The code is basically two simple lines of CSS and some JavaScript enclosed in pan.js — if Prototype and Scriptaculous are loaded. You can even have multiple items on one page.
<style type="text/css">
.viewport {border:1px solid #999; position:relative;
  height:200px; background-color:black; overflow:hidden;}
.viewport-image {position:absolute;}
</style>

<script src="/script/pan.js"></script>

<div class="viewport">
  <img class="viewport-image"
    src="/media/crowd.jpg" onload="new Pan(this);"/>
</div>

Nitty-gritty details: The script requires both Prototype and Scriptaculous, but frankly it could be rewritten for any other animation framework in about five minutes. It only uses the morph method from Scriptaculous, if you want to decrease your footprint slightly, you can substitute the two instances of morph with setStyle from Prototype.

Meta3

Monday, March 3rd, 2008

Wow, that’s good. Makes one believe that even IE is susceptible to reason.

Playing silly games [spilletmedbyer.dk]

Thursday, February 14th, 2008

Yesterday I spent about ten minutes assembling the map of the s-trains in this nice mashup game. It gave me an urge to do something silly and utterly pointless myself, and the result is stunning: Spilletmedbyer.dk

If you clicked the link, you’d know exactly what I did: Something Google Maps and a bit of data, and you can now guess the location of Danish cities and towns. You’re welcome.


Cheat mode:

javascript:answer(new GLatLng(currentQ.latitude,
  currentQ.longitude))

About meta

Tuesday, January 22nd, 2008

I’m quoting way too much from John Resig, but his points about the IE8 backward-compatibility meta tag discussion are well worth repeating, and there’s also way more poignant than most other comments I’ve been reading today:

The end result will be one in which: A) You’re either constantly dodging mistaken bullets from the Internet Explorer team as the push out new releases or B) They’re not going to do as many, if any at all, updates to the browser out of fear of breaking backwards compatibility. Honestly, I assume that B is far more likely, therefore you can be excited about looking forward to future, static, bug-laden releases of IE in the years to come!

Frankly, it’s a worthy cause for browser developers to shoulder some if the burden of cross-browser compatibility by including the ability for new browser versions to act like their older counterparts. But do you really trust Internet Explorer to do this well for each consecutive version?

Will IE10 include four rendering engines with their individual rendering and security bugs packed into one bloated product? Or, as Resig puts it, will development and innovation simply halt (as opposed to their already quite leisurely pace) because it’s much easier than maintaining multiple different “browsers” at any given time?

Do you apologize in code comments?

Sunday, December 30th, 2007

Apologetics in comments are usually a sign of the presence of design smell.

− from webmonkey

Gears doesn’t just do offline

Thursday, December 27th, 2007

Dion Almaer (of Ajaxian fame, of course) is writing a cool series about Google Gears. Apparently the nice people at Google have further-reaching ambitions than “just” an offline browsing api.

Reading through the Gears wiki you’ll sense that there’s no distinct direction for the developments of the tool, but there’s plenty of stuff to look forward to: The Location API, the Image Manipulation API (although it seems to be quite limited since you can’t manipulate images on the bit level and thus program your own manipulations), and the Messaging API.

Update: This new post in the series underlines the potential problem in the Image Manipulation API. You can only do the stuff with images that Google allows you to. No access to the actually content of the Blobs − only the meta data.

Chart with selectable legend [yui demo]

Friday, December 14th, 2007

I wrote about YUI Charts the other day and I guess my conclusion was that the library is promising, but still a long way from being perfect. Today, I have been using it in a real-life setting a found that I wanted to do some stuff that’s isn’t supported out of the box in order to build something that looks like this:

YUI Chart Demo Screenshot

Merge multiple dataset into one graph

By default the library accepts one datasource containing a category, which is turn can have multiple values. This would be an array, which looks like this in Yahoo’s own documentation:

var data =
  [{ month: "January", rent: 880.00, utilities: 894.68 },
   { month: "February", rent: 880.00, utilities: 901.35 }];

This looks great paper, but when preparing data from the database it’s requires some clever trickery to set up such a datasource. Instead, I wanted to prepare several arrays containing label/value pairs and merge them into a data source. For example:

var rentValues =
  [{label: "January", value:880.00},
   {label: "February", value: 880.00}];
var utillitiesValues =
  [{label: "January", value:894.68},
   {label: "February", value: 901.35}];

The example includes a simple piece of code, which merges these two (or more) datasets into something which is edible for the YUI datasource. Make sure that the label properties are the same in all datasets though. Otherwise, you’ll see strange results..

Show a colorful legend

Even though you’ll actually be sending all the required information to the chart library, it won’t build a chart legend for you. Which is bad. Instead, the documentation shows how to set up something similar in HTML. In this case, I wanted to allow selection and de-selection of items on the chart and have the visualization scaled accordingly.

In the example I’m using the same data to build both a data chart and a HTML form, which displays the name and color of each line on the chart — and which handles a redrawing after selecting and deselecting individual items on the form.

Abstract some of the heavy lifting

Yahoo’s own examples are pretty cool, but drawing a chart isn’t exactly a one-line job. I wanted to make it — so I’ll be able to do something like this:

var rent = {displayName:'Rent', data:rentValues};
var utilities = {displayName:'Utillities',
  data:utillitiesValues};

prepareChart('container',
  [rent, utillities], 'formatFunction');

…where container is the name of the html elements holding the chart and the legend, and where formatFunction is a reference to the JavaScript function responsible for formating data on the Y-axis.

The data objects can be expanded slightly to include both information about the color of the line and when the dataset should be shown by default:

var rent = {displayName:'Rent', data:rentValues,
  hidden:true, color:'#cc0022'};

In action…

» See it in action

The example generates some random data about a fictive web site and displays “New signups”, “Total number of users”, “Active users” and “Returning users” for the past two months (if somebody has ideas for real data to plot, please let me know). This it simply does:

var signupsPerDay = {displayName:'New signups',
  data:randomSignupUsers};
var numusersPerDay = {displayName:'Total number of users',
  data:randomTotalUsers, hidden:true};
var activeusersPerDay = {displayName:'Active users',
  data:randomActiveUsers};
var returningusersPerDay = {displayName:'Returning users',
  data:randomReturningUsers};

prepareChart('users',
  [signupsPerDay, numusersPerDay,
    activeusersPerDay, returningusersPerDay],
  'usersCountFormat');