Making Your Own Growl Widget With Dojo

September 8th, 2009 by Eric Leave a reply »

Learn how to properly separate XHTML, CSS, and Javascript by creating your own Growl Widget.

Demo

Upon page load, this form no longer submits but displays a notification instead.

View Source

Introduction

Designing for code-reuse is one of the most important acquired skills for a developer. Unfortunately, Javascript widgets tend to contain large amounts of embedded markup and styles. I blame this primarily on lackluster development & deployment of client-side code, as well as the fact that very few Javascript libraries are truly enterprise-ready .

In this tutorial, you’ll see some best-practices found in the Dojo Toolkit for name-spacing widgets and structuring resources.

1 Requirements

We want a growl widget that:

  • Will look good
  • Will stack with other notifications
  • Will disappear after a period of time
  • Will close immediately of the user clicks it
  • Will not disappear if the user hovers over it

Javascript Growl Screenshot

2 Marking it up

The markup needed for the widget alone is simplistic; however, since we’re using dojo templating, we need to add in just a little bit more code:

First, we’re tying mouse events onMouseOver, onMouseOut and onClick to the widget functions _hoverOver, _hoverOut and close, respectively.

Second, we’re replacing our placeholder text with a template tag which will be replaced with the variable message (more on this later).

3 Styling the markup

Since the markup is separate from the presentation, modifying the look-and-feel is a cinch.

4 Scripting the widget

5 Calling the widget

Include Dojo and the script in your page:

<script src="/scripts/dojo/dojo.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
    // Tell dojo where to find the "demo" namespace
    dojo.registerModulePath("demo", "/scripts/demo");

    // Require the notification script for this page
    dojo.require("demo.ui.Error");
</script>

Now simply instantiate the class:

new demo.ui.Error({
    message: "Howdy there!"
});

6 Resources

Here’s everything you need to get started:

Leave a Reply