Tag Archives: web development

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.

Advertisements

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.


Get Value of Unknown Type From Unknown Object

In a previous post I mentioned a content management system I built for dynamically creating email content to notify users of events.  The system is delivered via a RESTful web service that is called from disparate websites and programs within our software ecosystem.  The basic requirement of the content builder is that those calling systems only need to provide a few key values.  From that information it can determine what database object to gather data from and what content templates to use for building the email notifications.

The design of the system rests on the Abstract Factory design pattern.  This allows the system to determine at run time what objects to create.  In doing this the system uses reflection in a number of ways, one I discussed in a previous post mentioned above.  Another I’m going to share in this post.

The system is passed an object which contains all the possible key fields needed to determine what data and content are needed.  Depending on which key fields are populated, the system will create the needed data objects and apply the correct rules and templates for constructing the template.

Example Class:

     
namespace Extensions
{
    public static class ObjectExtensions
    {
       public static T GetPropertyValue<T>(this object sourceObject, string key)
       {
         if (sourceObject.GetType().GetProperty(key) == null)
            return default(T);
         return (T)sourceObject.GetType().GetProperty(key).GetValue(sourceObject, null);
       }
    }
}

Explanation:

The class is static because I like to write these sort of methods as extensions.  I find them easier to use as a developer and really we just want to extend this method to any object.   The method returns the generic type T because we don’t know what type the property we’re looking up is until run time.

The method first checks to see if the property(key) being requested exists.  If  it does not we return the default value of the generic type.  In my system this works fine.  Returning a null for a string or a zero for an integer will net the same affect because it’s as good as it not being populated.  In other implementation you may want to throw an error here.

If the property exists then the value is returned to the caller it’s all done.  You might ask, what if the property they pass as the “key” does not have a type of “T”?  I contemplated that, one option could be to just return the default of the type T in that scenario.  Instead, I decided not to handle that and allow the .Net framework to bubble the error up to the caller and allow it to make a decision on what to do.  I’m not a big fan of validating methods are being called correctly in my logic layer or adding too much error handling.  If not done correctly errors can be masked from the calling program and hidden. Below are a few unit tests that show how the method works.

Unit Tests:

[TestClass]
public class ObjectExtensionsTests
{
   public class SourceObject
   {
      public int Id { get; set; }
      public string Ids { get; set; }
   }

   [TestMethod]
   public void ValueExistsAndIsReturned()
   {
      var s = new SourceObject {Id = 123456};
      Assert.AreEqual(123456, s.GetPropertyValue<int>( "Id"));
   }

  [TestMethod]
  public void ValueDoesNotExistsAndDefaultIntValueIsReturned()
  {
     var s = new SourceObject { Id = 123456 };
     Assert.AreEqual(0, s.GetPropertyValue<int>("Id2"));

  }

  [TestMethod]
  public void ValueDoesNotExistsAndDefaultStringValueIsReturned()
  {
     var s = new SourceObject { Ids = "123456" };
     Assert.AreEqual(null, s.GetPropertyValue<string>("Id2"));

  }

  [TestMethod]
  public void WrongTypeErrorReturned()
  {
    var error = false;
    try
    {
      var s = new SourceObject { Id = 123456 };
      Assert.AreEqual(null, s.GetPropertyValue<string>("Id"));
    }
    catch (Exception)
    {
       error = true;

    }
    Assert.AreEqual(true, error);

  }
}

There you have it. A simple extension method to get the value of an unknown property on an unknown object.


Returning Errors in a WCF RESTful Web Service

While writing web services I’ve used several different methods for returning errors. A very common method is to return null or if the response is a string return the word error or a message stating there was an error. That works, but I’ve never really been a big fan.

Example:

public object GetSomething(string param)
{
try
{
var returnObject = new object() = some code here
return returnObject;
}
catch (Exception ex)
{
return null;
  or
return new object();
 or
 some variation;
}

}

This method doesn’t really seem to comply with best practices for being RESTful or for OOP. It gets you by, but it’s kind of smelly.

More recently, especially with RESTful WCF Web Services that are returning complex objects, I’ve added DataMembers to the DataContract that include an error Boolean and error message along with the object(s) I’m returning as a DataMember.

Example:

[DataContract(Name=”returnObject”)]
public class returnSomeObjects
{
[DataMember]
public IList <someObject> { get; set; }
[DataMember]
public bool Error { get; set; }
[DataMember]
public string Message { get; set; }
}

Then in the error handling above:

catch (Exception ex)
{
return new returnObjects() {Error = true, Message = “ex.Message”};
}

I like this method more because it always returns the same object and the calling process can make a decision based on error being true or false. Even if you don’t have complete control of the returning object(s); for instance when wrapping a legacy class library with a service, you can just make the object a DataMember on the DataContract and away you go.

The problem with this method is the http response is a 200 ok, even though an error occurred. So, it’s not as smelly, but still not the best practice. Recently I’ve begun to favor a more organic approach. Something that is more RESTful in nature, that is modifying the http status code to reflect that an error has occurred.

Example:
catch (Exception ex)
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
response.StatusDescription = “A unexpected error occurred!”;
}

You could evaluate the exception and return codes based on certain situations, I use the above for unexpected errors. You could also make the response.StatusDescription the exception message. The calling process can now key off of the http status code and handle the situation as required by it’s own system and rules.

You might ask, why modify the status code? If you just simply throw the error you achieve something very similar, that is a HTTP status code other than 200 ok. The issue, for me at least, is you get a 400 bad request. Which is a little misleading to the caller and not exactly true if somewhere in my data or logic layer an error has occurred.

So I like to add a little control. You can evaluate for invalid parameters or data and still return the 400 bad request when appropriate, but for unexpected errors, I like returning the 500 Internal Server Error.

I should mention I’m using this for internal web services so I do have more latitude in what I show to the calling processes and systems, however, I see no reason why using standard http response codes would be a problem in a public API.

Additionally, this method adds more consistency to what a calling process will get when errors occur. For example, with the previous methods if your service is unreachable they would get a different response then if it is reached and a custom error is returned. In other words, they can always evaluate the response codes that are native to http giving you a more RESTful response.


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.


%d bloggers like this: