Tag Archives: Javascript

JavaScript: Not for the faint at heart?

JavaScript: A tool too sharp?

Script# (Script Sharp) – writing javascript in C#

Both Jimmy and roy have great posts discussing JavaScript. Roy is looking at it as a C# developer lured by the many, many articles about how jQuery is the only thing that makes JavaScript worth using and using Script# to abstract away some of the messiness and pain usually associated with writing JavaScript. Jimmy discusses the merits of JavaScript itself and how it has changed how he approaches writing C# code.

One thing I like to point to is a great quote I heard on Twitter

Java is to JavaScript as ham is to hamster

hamster2.jpg

JavaScript actually has more in common with Scheme or Lisp than it does Java or C#. I first realized this when I saw that Douglas Crockford had re-written all of the examples in The Little Schemer
in JavaScript. It’s easy to miss that fact when you see all of the pseudo OOP noise like “var foo = new Foo();”. But when you see how trvial it is to implement something like a map method in JavaScript, you realize how powerful the language can be. Most of the hatred for JavaScript comes from two things I’ve found:

  1. Broken DOM implementations – every browsers implementation of the DOM is broken in one respect or another.
  2. A misunderstanding of either scope or inheritance.

Roy has a great point about the lack of good tooling surrounding JavaScript. There are excellent libraries like jQuery and PrototypeJS, but the usual tool support, intellisense, re-factoring, profiling, is a little more difficult to come by. I’ll address this in another post as I feel a lot of people are new to JavaScript and are struggling along with some substandard tools.

jQuery tip – beware anonymous functions in your event handlers

jQuery makes it really easy to wire up event handlers using anonymous functions.

<script type="text/javascript">
    $(document).ready(function()
    {
        $("#Button1").click(function(event)
        {
            alert("You Clicked Me!");
        });
    });
</script>

In this case you are just wiring up one element to an event. Lets consider the case where you have a larger number of elements on the page and want to hook up to a click event on each one.

		$(document).ready(function(){
			for(var i =0;i<10000;i++)
			{
				$("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
			};
			
			$(".clickybutton").click(function(e){
				alert(e.target.id);
			});
		});

In this case, a new anonymous function will be created for each element on the page. This can waste a lot of memory. It’s sometimes better to use event delegation. That is, to let the event bubble up to a single containing element which then determines a course of action for the element that was clicked.

		$(document).ready(function(){
			for(var i =0;i<10000;i++)
			{
				$("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
			};
			$("#bigContainer").click(function(e){
				if($(e.target).hasClass("clickybutton"))
					alert(e.target.id);
			});
		});

If you want to learn more about JavaScript, I’d recommend reading the following books:

Why these jQuery worst practices aren’t.

jQuery … Worst Practices

In this post, Steve Wellens tries to make the case for two common patterns your run across when using jQuery as “worst practices”. Practices that are either superfluous or harmful to your code.

1) Wiring up events using unobtrusive JavaScript.

Instead of wiring up your elements events using jQuery, instead you should set the OnClientClick property of the ASP.NET Web Control in question and call whatever JavaScript you want to handle the event.

Instead of this:

    <script type="text/javascript">

        $(document).ready(function()
        {
            $("#Button1").click(function(event)
            {
                alert("You Clicked Me!");
            });
        });

    </script>

Do This:

    <asp:Button ID="Button1" 
                runat="server" 
                Text="MyButton"                
                OnClientClick="alert('You Clicked Me!');" /> 

His reasoning is as follows:

You might want to change event handlers dynamically depending on some condition in the page. If you need to assign a common event handler to several objects on a page, it makes sense to do it in one place. As a matter of fact, that’s the beauty of jQuery. But for a single event on a single control….NO.

On can debate whether or not a worst practice can really be applied to a single, specific , one-time event or not. But there are other reasons why you might want to hook up events to a single element using jQuery. one being that you can’t hook up multiple event handlers using OnClientClick or HTML’s OnClick event, only a single event handler can be assigned. If you are using the observer pattern in your JavaScript, you may have multiple observers that want to subscribe to your buttons click event. But a really strong argument could be made for using the OnClientClick property simply due to ASP.NET’s suck-ass way of handling client IDs.

2) Chaining can lead to unreadable code.

In a badly written example, he states that chaining calls to jQuery makes the code unreadable. I’d suggest re-formatting the code in this manner to make it legible and allow for a tighter minimization.

$("div.highlight")
  .css("color", "yellow")
  .css("background-color", "black")
  .css("width", "50px");

Of course, you wouldn’t write jQuery code like that and call the css method multiple times. Ideally, you would just set a class or at the very least pass in a set of properties in an object.

$("div.highlight").css({
  color:"yellow",
  background-color:"black",
  width:"50px"
});

3) Comment your code.

// get all the Divs with the highlight class and
// format them and set their width

var Divs = $("div.highlight");
Divs.css("color", "yellow");
Divs.css("background-color", "black");
Divs.css("width", "30px");   

I like this explanation by Jeff Atwood best. If you need comments to explain WHAT your code is doing, you need to use better names and/or write better code. Comments are best when used sparingly and explain the WHY of the code. Why did you choose to use a particular algorithm

Modern JavaScript Development: Scope

After hearing an interview Scott Hanselman did with Scott Cate about JavaScript a while ago, I decided to use one of my presentations into a screen cast. In this two-part screen cast, I cover how scope works in JavaScript and how we can use object literal notation to fake namespaces.

Making JavaScript Less Painful part 1

Making JavaScript Less Painful part 2

I’m still finding my way around screencasts. Eventually I’ll upload these to vimeo, screencasts.com,, and youtube as well as making them embeddable and providing embed code.

Modern JavaScript Development: Reflection in JavaScrpt

Sometimes you want to find out what members an object exposes. There’s a pretty simple way to do this. A simple for-in statement.


for(var member in obj){ alert(member); };

No really, that’s it. No “imports” or “using” statments. No complicated classes to memorize, no unwrapping or casting. Just for-in over an object. One caveat, this will show you ALL of the objects members and it doesn’t distinguish between members declared directly on the objects and members inherited through the objects prototype. What if you just want to find the methods on an object? I’ve created two helper functions that will return just the methods(functions) of any JavaScript object.

Object.prototype.getAllMethods = function(){
var memberArray = new Array();
for (var method in this) {
if (typeof this[method] == 'function') {
memberArray.push(method);
};
};
return memberArray;
};

Object.prototype.getOwnMethods = function(){
var memberArray = new Array();
for (var method in this) {
if (typeof this[method] == 'function' && this.hasOwnProperty(method)) {
memberArray.push(method);
};
};
return memberArray;
};

In the getOwnMethods function we use the hasOwnProperty function to discriminate between methods declared in the object and methods inherited through the prototype.