Tag Archives: JavaScript

Event Namespacing: It’s A Good Idea

If you’re a web developer and use jQuery chances are you have had, or will have, the need to attach event handlers to your page elements.

With jQuery you can do this in a number of ways .on, .bind, directly with .click (blur, mouseout, etc…), and more.  For more information regarding adding handlers and removing them see the jQuery API documentation.

A quick example using .bind:

$( "selector" ).bind( "click", function() {
//do something;
});

And if you ever needed to remove your handler you could do something like:
$( "selector" ).unbind( "click");

This is all very simple and works great.  However, what if you need to remove a specified handler?  For example, if you’re writing a plugin and need to remove only the plugin’s custom handlers.

Both jQuery functions .off and .unbind allow you to pass in the method signature to remove the specified handler. However, this requires you to maintain a reference to the handler which may not be ideal.

This is where event namespacing can come in handy.  Adding a namesspace to your handler when you attach it allows you to safely remove it later without removing all event handlers of the same type.

Here are the same bind and unbind methods using a namespace:


$( "selector" ).bind( "click.mynamespace", function() {
//do something;
});

$( "selector" ).unbind( "click.mynamespace");

Namespaces gives you the flexibility to unbind specific event handlers while maintaining the ability to unbind by event type or all handlers at once.  It can also be used in the same way to trigger a specific event handler.  And it’s a good practice to easily identify custom event handlers, especially when developing plugins.


Simple Method for Adding Tooltips

There is no shortage of plugins and techniques for adding tooltips to elements on your website.  I’ve used a lot of them, and most work pretty good.  However, I have found some to be a little cumbersome and bit of overkill.  Here’s an example of a very simple jQuery solution that I’ve used in a number of cases for selects and inputs.

Take for example the following HTML:

Which of course will render as:

With just a few lines of jQuery and a little CSS we can add a tooltip to each of these inputs that will open on hover.
jQuery:
 


CSS:


Now hover over the input and you’ll get the following:

How it works:

The jQuery simply binds the hover function to the inputs which creates the event listeners for mouseout and mouseover for each input.

On mouseover a span is added to the DOM after the target element.  Notice it uses the width and position of the target element to calculate the placement of the span.

On mouseout the span is located using the class as a selector and removed from the DOM.

The CSS can really be whatever you want for style purposes.  What is important is the position and z-index.  Depending on the makeup of the other elements on your page you’ll need the position set to absolute to enforce the location of the span that is created on hover.  And, I like to use a high z-index so that the help text will appear above any near by elements.

If you like this method and want to use it with more flexibility for positioning I created a plugin called Easytip.  You can find more information on the plugin and download it here.


Object Reflection In JavaScript

Reflection is a powerful technique that I’ve used a lot in C#. On several occasions I’ve found some uses for this technique in JavaScript too. Most recently, I was writing a test harness for a RESTFul web service to allow our QA folks a easy way to test it. Typically, when I’m writing these kinds of things I have a couple objectives in mind.

First, I don’t want to turn the testing tool into a maintenance item. That is, if there are updates to the software being tested (a web service in this case) I don’t want to have to update the tool.

Second, I don’t want to add another uncontrolled variable to the testing.   Meaning, I don’t want the testing tool to require extensive QA or to create a layer of possible bugs to be validated anytime QA finds an issue with the software being tested.

Finally, I don’t want to spend a lot of time on it and I’d like to reuse it. It’s an internal tool that is usually being used by a semi-technical person and has a very specific purpose, being pretty isn’t one of them. And, if I can use it again, for another web service in this case, double bonus!

In the case of the RESTFul Web Service testing tool I accomplished this in two ways.

First, I build the inputs for the service by parsing the web service schema (.xsd) dynamical. This way, if new inputs are added I don’t have to update the testing tool. I probably write a post on that part another day.

Second, I output the results (which are returned in JSON) to a web page using reflection after the JSON object is parsed to a JavaScript object.

Here is an example of how I do it:

Consider the following object. It has a set of properties, a nested object, and a function.

var obj = new Object;
obj.FirstName = “John”;
obj.LastName = “Smith”;
obj.FullName = “John Smith”;
obj.Address = “Main Street”;
obj.Phone = “999-999-9999”
obj.GetName = (function () {});
obj.History = new Object();
obj.History.PreviousAddress = “South Street”;
obj.History.PreviousPhone = “888-888-8888”;

All I want to do is print each property and it’s value to the screen. And, if there is a nested object I want to print it’s properties too. This will allow the return results to be validated.

To do this I use a script like this:

function DisplayObjectProperties(obj) {
for (prop in obj) {
var text = “”
if(typeof obj[prop] != “function” && typeof obj[prop] != “object”){
text = prop + “: ” + obj[prop];
}
else if (typeof obj[prop] === “object”) {
DisplayObjectProperties(obj[prop])
}
$(“body”).append(“<div>”+ text + “</div>”);
}
}

Nothing too much going on here, just a loop through the object and appending each property name and it’s value to an html element.  The important thing is to test the type, so you can handle nested objects, arrays, functions, etc however you might want to.  In my case, if there is a nested object I want to display it’s properties too.  I do that with a recursive call to the function passing the nested object.

Call it:  Just pass the object to the function it will do the rest.

DisplayObjectProperties(obj);

Results:

FirstName: John
LastName: Smith
FullName: John Smith
Address: Main Street
Phone: 999-999-9999
PreviousAddress: South Street
PreviousPhone: 888-888-8888

Floating Sidebar With CSS

Floating sidebars are a great method for keeping menus, share buttons, and other information in front of users as they scroll down the page. There are a number of jQuery plugins that work great for this, but in some cases jQuery might be overkill. For example, if you need to keep informational or help text that is static in front of the user.

A simple way to create a floating sidebar is to use CSS. Take a look at the side bar on the left and scroll down the page this jsfiddle test. Notice, it stays in view the entire time. To achieve this all we have to do is create a div with the following class.

.sideBar
{
position: fixed;
z-index: 1000;
}

The magic is “position: fixed”, it’s what makes the sidebar stay where you want it to. Depending on what else you have on the page, and perhaps if you want it to float outside the container the div is in, I like to use z-index to make sure it overlaps how I want it to.

Now that you have it floating you need to position the div and style it by adding another class like below. In this case the div will float on the left and start below the header of the page.

.sideBar.boxLeft
{
width: 300px;
float:left;
padding: 0px 0px 0px 0px;
left:75px;
background-color:#eee;
top:30%;
}

There you have it, in just a few minutes you have a quick and easy solution for creating a floating sidebar.


Add CSS Class Recursively With jQuery

The Function:

function addCSSClassRecursively(topElement, CssClass) {
    $(topElement).addClass(CssClass);
    $(topElement).children().each(
            function() {
                 $(this).addClass(CssClass);
                 addCSSClassRecursively($(this), CssClass);
            });
}

Pretty simple. The first line adds the class to the element passed in. Next, using the jQuery.children() and jQuery.each() functions it iterates through each child element adding the CSS Class and then calls itself to add the CSS class to each of the child’s children elements.

Calling it:

$(function() {
   addCSSClassRecursively($('#div1'), 'MasterCssClass');
});

In my implementation I call the function when the DOM is fully loaded, using the jQuery.ready() function. I just pass in the parent or top level element I want to start adding the class at and the functions does the rest.


Unit Testing JavaScript with MSTest and JSTest.Net

JavaScript: A necessary evil

I’ve always found that while JavaScript was a powerful tool for web development it could be a real pain to test and debug.  Until now I pushed through the pain with good old fashioned manual testing and the debugging tools available in web browsers.  Recently, I was developing a web page that needed a lot of client side calculations and data manipulation. I decided it was time to man up and find a way to unit test client side JavaScript.

I Wanted

  1. Integration with MSTest
  2. Writing unit tests with server-side code as I do for C# code
  3. Running JavaScript and C# unit tests together in harmony
  4. Nothing to install so others can just start using the testing library
  5. No web browser required

Surprise and Delight
A few minutes on Google and I found a solution that appeared to be the answer. Before I go on, I should mention I found several testing libraries so there are many options. Most of which integrate with MSTest and most other testing frameworks.

The winner is
I selected to use JSTest.Net

It was pretty simple to get up and running:

  1. Just download the dll from JSTest.Net
  2. Made a reference to it in my test project
  3. Added a couple using statements in my test class
  4. Started writing tests

Consider this JavaScript example

function calculateMarketPrice(value, quantity, factor) {
    return (value / quantity) * factor;
}

It’s pretty simple, send in a few parameters and return a value.  However, testing this manually and debugging through the web browser is not always as simple, especially if it’s implemented on complex web pages.  In a lot of cases it’s tedious and inefficient.  Even worse it could be ineffective and bugs could be missed.  For example, maybe there’s a rounding issue?  Or maybe a null parameter won’t be handled as expected.  We just don’t know unless we test for it.  And when testing is difficult it’s more likely to be missed or god forbid skipped.

Test Class Example

using Microsoft.VisualStudio.TestTools.UnitTesting;
using JSTest;
using JSTest.ScriptLibraries;

namespace JavaScriptTestProject
{
    [TestClass]
    public class CommonJavaScriptTests
    {
        private readonly TestScript _commonTestScript = new TestScript();

        public CommonJavaScriptTests()
        {
            _commonTestScript.AppendFile(@"..\..\..\..\MyJavaScriptTest\MyJavaScriptTest\JavaScript\Common.js");
            _commonTestScript.AppendBlock(new JsAssertLibrary());
        }
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void GivenValueQuantityAndFactorTheCorrectMarketPriceIsReturned()
        {
            _commonTestScript.RunTest(@"assert.equal(99.26, calculateMarketPrice(49630, 50000, 100));", true);
        }
    }
}

A quick overview
The library uses a class called TestScipt as a wrapper  to command line scripts (CScript). Before writing tests it’s necessary to add the script file you’ll be testing and any additional libraries to the TestScript.   In my example I used the AppendFile method to add my js file and the AppendBlock to add the assertion library included with JSTest.   According to the documentation there are other assertion libraries and mocking libraries available but I have not tried them yet.

Once the scripts are appended to the TestScript class the RunTest method can be invoked.  It takes the script block to be tested as the first parameter and has an overload that includes a boolean to turn debug off and on.  When debug is on and you select to debug your test it allows you to step into the debug test script and from there into your script. This is awesome. Not only do I get to easily test every scenario I can think of, I get to debug it too!

JsTest Documentation

Other Things

  • My example uses MSTest but it works with other test frameworks
  • The documentation says it only works with VS2010, But I have it working in 2008

Conclusion
With testing libraries that are compatible with most frameworks available there are no excuses for not covering JavaScript with unit tests. And the integration with the visual studio just in time debugger is icing on the cake. It’s also worth noting I’ve since used this library for more complicated tests that included date manipulation and JSON and found it just as effective.


%d bloggers like this: