Introduction
Useful Javascript extensions
asp.net

Useful Javascript extensions

In my previous post I added the extensions.js-file to my JavaScript library. I did this because I feel there are some things that I often do and I abstracted them out to a kind of library on top of jQuery. I will walk you through the different functions it offers. You can of course take a look at the source where everything is fully documented in the Visual Studio documentation format (you’ll also get nice intellisense when you reference it). This post is all about the client-side, so no .NET, no posting, just plain old HTML and JavaScript.

1. Hash

The Hash is a new type of Object (~to a .NET-class) that comes from my time as a user of the Prototype-library. When crossing over to the jQuery-side I really missed this little class. You can best compare it with the .NET Dictionary class. It is basically a key-value collection. (This is a stripped down version of the Prototype-class and by no means is it as powerful or as performing as the Prototype object, but it serves its purpose). Example:

<script type="text/javascript"> var h = new Hash(); $(document).ready(function () { $("#btnAdd").click(onBtnAddClicked); var s = "My name is {0}. The year is {1}"; alert(s.format("Kenneth", new Date().getFullYear())); }); function onBtnAddClicked() { h.set($("#txtKey").val(), $("#txtValue").val()); $("#txtKey").val(""); $("#txtValue").val(""); ShowHash(); } function ShowHash() { var vals = $("#values"); vals.html(""); h.keys().each(function (key) { vals.append("Key: " + key + ": "); vals.append("Value: " + h.get(key) + ""); vals.append("
"
); }); } </script> <p> Key: <input type="text" id="txtKey" /> Value: <input type="text" id="txtValue" /> <input type="button" id="btnAdd" value="Add" /> </p> <hr /> <p>Contents of the Hash:</p> <p id="values"></p>

2. Array

The reason for adding this is also a remain of my days as a Prototype user. I have added some functionality to the JavaScript Array-class (Most of them mimicking .NET counterparts):

  • compact: Removes null and undefined elements from the array.
  • removeAt: Removes the element at the specified index.
  • remove: Removes the element from the Array.
  • sortNumericAsc / sortNumericDesc: Sorts the Array asc or desc supposing they are all numbers. Use this if you don’t want number 10 to be before number 2 when sorting a numerical array. (The default implementation treats all items as Strings)
  • indexOf: If the browser doesn’t implement this method, it will be added.
  • each: Unlike the jQuery each, this will pass the element as the first parameter and the index as a second parameter. No screwing around with the scope here.

I have not included a sample for this, but I’m sure you can see that these methods are useful in every day use.

3. Function

And again some Prototype juice to be added to our toolset.

  • Bind: Binds a scope to a function and returns the function. This way you can control the this-identifier when you when you are calling a function. Very useful when you are handling events.
  • Defer: This will defer the execution of the current function until the call-stack is empty. Use this if you want to make sure all other things are done first.
  • Delay: Executes the function after the specified amount of time. More of a shortcut to the setTimeout-method. It’s just easier syntax.

4. String

These are some useful extensions to Strings.

  • getNetDate: When we will call .NET-web services .NET-datetime objects will be returned as “funny” strings (basically the number of ticks and some proprietary prefix ). This method will convert it nicely to a JavaScript Date-object.
  • format: Exactly the same function as the .NET String.Format. Example: var s = "My name is {0}. The year is {1}"; alert(s.format("Kenneth", new Date().getFullYear()));

5. jQuery extensions

Last but not least I added some useful things jQuery plugins. Nothing big here, just small utilities we use all the time. I will skip some items here as I will explain them in a later post when I will be talking about connecting jQuery and .NET.

  • getInt: Does the same as the jQuery attr()-function. However it will parse the value as a Number so that you don’t have to convert it every time if you know the value is a Number.
  • noLink: Adds a handler to an element so that the default behavior is prevented. You can use this when using an a-tag but you don’t want it to execute the action. You can do this in jQuery but then you will have to add it to your event-handler. I extracted this, so your event-handler just has to do what it’s there for: handling the event and executing the appropriate actions. It shouldn’t be dealing with whether the link should be executed or not (unless that’s part of the behavior).
  • stopPropagation: Basically the same thing as noLink, except this time it refers to whether the click-event should or should not bubble.
  • isFirstChild: Quite self-explanatory.
  • Selection methods: Often you find yourself selecting and deselecting items on a page. Usually when you select an item you want to apply a different style (similar to the hover pseudo class). These methods mimic the behavior of the :hover pseudo class, but for “selected” items. It does so by adding or removing a class to the item. Which class this is, is defined as a constant on top of the file. - SelectItem
  • DeselectItem
  • isSelected
  • toggleSelection

Example with standard selecting and mutually exclusive selection:

<script type="text/javascript"> $(document).ready(function () { //$("ul li").click(onLiClickedExclusive); // Mutually exclusive $("ul li").click(onLiClicked); // Standard }); function onLiClickedExclusive() { $("ul li").deselectitem(); $(this).selectitem(); } function onLiClicked() { $(this).toggleSelection(); } </script> <style type="text/css"> li{ background-color: White; color: Black; cursor: pointer; } li.selected{ background-color: red; color: White; } </style> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> </ul>

 

All right, that was it for this post. As you may have noticed, I skipped the callAsmx-method and the getAll-method. Stay tuned for more info on these methods.

Kenneth Truyers
View Comments
Next Post

AJAX with jQuery and web services

Previous Post

Setup and tools