How Good C# Habits can Encourage Bad JavaScript Habits:
Part 3 – Function Scope, Hoisting, & Closures

This is the third post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.

The first post covered the following topics:

  • 1. Having Variables & Functions in Global Scope
  • 2. Not Declaring Arrays & Objects Correctly

The second post covered the following topics:

  • 3. Not Understanding False-y Values
  • 4. Not Testing & Setting Default Values Correctly
  • 5. Using the Wrong Comparison Operators
  • 6. Not Using the for…in Statement Correctly

Introduction

This post continues to focus on areas where C# developers tend to make bad JavaScript decisions based on their previous training. The languages are similar enough syntactically that C# developers tend to not invest the time to learn JavaScript’s differences.

The following post points out several misunderstandings that can get you into some confusing situations.

How Good C# Habits can Encourage Bad JavaScript Habits:
Part 2 – False-y, Testing and Default Values, Comparisons, and Looping

This is the second post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.

The first post covered the following topics:

  • 1. Having Variables & Functions in Global Scope
  • 2. Not Declaring Arrays & Objects Correctly

Introduction

This post continues to focus on areas where C# developers tend to make poor decisions when writing JavaScript based on their previous training. The languages are syntactically similar enough that C# developers tend to not invest the time to learn JavaScript’s differences.

The following post points out several misunderstandings that can get you into some confusing situations.

How Good C# Habits can Encourage Bad JavaScript Habits:
Part 1

This is the first post in a multi-part series covering common mistakes C# developers tend to make when they first start writing JavaScript.

Introduction

Many people come to jQuery and believe that their knowledge of a previous classical language (C#, Java, etc) will help them be successful at client-side scripting. You can use your classical language skills to accomplish a large amount of functionality with jQuery. However, the more client-side code you write you will find yourself uncovering strange bugs because you didn’t take adequate time to learn JavaScript properly.

“…it turns out that if you have absolutely no idea what you’re doing in the language you can still generally make things work.” –Douglas Crockford, Yahoo!’s JavaScript Architect, Douglas on JavaScript -- Chapter 2: And Then There Was JavaScript

This article is targeted for developers that use jQuery but haven’t invested the time necessary to learn JavaScript. The intent is to help you avoid some common mistakes when moving from a classical language (Java, C#, etc) to JavaScript.

jQuery is a library that is written in JavaScript. It is important to remember that you will always be writing in JavaScript when using jQuery. It is inevitable that you will run into native JavaScript concepts that are foreign to the classical language proficient developer. Taking the time now to be proficient in JavaScript will increase your client-side code quality, efficiency, and decrease code maintenance.

Creating an Ajax Component:

Handling Errors and Loading Notifications with Publish and Subscribe

This is the second post in a multi-part series on creating a JavaScript component for handling your Ajax requests in front-end development across your enterprise. You can find the first post here:

In the last post we covered some introductory topics for creating your own JavaScript utility library, which wraps functionality for Ajax. We’ll start where we left off. Our first step will be to add a few tweaks to our library to make it more usable:

var mySiteAjax = ( function( $ ) {
  return (
     function( params ){
      var settings = $.extend({
        url: "", 
        spinner:  undefined, 
        dataType: "html",
        data: "",
        type: "GET",
        cache:  false,
        success:  function() { }
      }, params );

      $.ajax({
          beforeSend: function() { 
            $( settings.spinner ).show();
          },
          url: settings.url,
          dataType: settings.dataType,
          type: settings.type,
          data: setting.data,
          success: settings.success,
          complete: function() {
              $( settings.spinner ).hide();
            }      
        });
    } 
  );
})(jQuery);

We’ve done two things to our old example. We’ve added new parameters for type and data that could be passed in. Additionally, we’ve removed a named function and returned an object literal. This enables easier usage:

mySiteAjax({
  url: "myUrl",
  success: function( data ) {
    //do something with the data here
  }
});

Although a good start, this solution is not yet satisfactory as we are not yet handling errors in any capacity. How do we handle errors and display messages to the user? Additionally showing and hiding of loading notification images is present but not customizable. What if a page doesn’t want to do a simple showing and hiding of load images? How can we decouple the notifications from our Ajax component library?

Enterprise jQuery Manifesto

EnterprisejQuery.com is run by appendTo.

appendTo launched in October of 2009 with Mike Hostetler and myself having the vision of providing enterprise grade services for jQuery. Both of us have a long history of experience in the large enterprise as well as startups. We’ve worked in the trenches and have seen first hand the challenges that organizations face.

appendTo has a diverse set of enterprise experience with the 7 additional employees we’ve hired: Levi DeHaan, Scott González, Elijah Manor, Doug Neiner, Andrew Powell, Leah Silber, and Andrew Wirick. Of which we’ve worked at, contracted for, and consulted with several large organizations such as: AOL, Apple, Blue Cross Blue Shield (NE), BMW, Bureau of Land Management (BLM), Chrysler, CSC (Computer Sciences Corporation), Ford, GM, Guardian Life, IBM, Microsoft, Motorola, National Instruments, National Renewable Energy Lab (NREL), Union Pacific Railroad, Xcel Energy, and Zurich International.

Every organization is different, but core themes naturally emerge. In July of this year, appendTo launched EnterprisejQuery.com to cater to this audience and it has sparked a debate about “what is the enterprise” and “does jQuery fit in the enterprise”.

Enterprise Strategies for Adopting HTML5 Part 1:
Simplified Syntax & Semantic Elements

This is the first post of a multi-part series covering strategies that you might use to adopt HTML5 in your current or future corporate websites.

Introduction

HTML5 has many features which you’ve likely heard about or seen in various blog posts. With all of the publicity HTML5 has begun to hold weight as a marketing term and businesses are paying attention. In the near future we’ll see businesses want to leverage HTML5 to send a message that they are innovative and competitive.

Unfortunately many of the HTML5 features are not fully implemented in the newest versions of modern browsers. Older browsers lack any HTML5 support. This leaves us with a key question: “To what extent can I use HTML5 inside my enterprise application?”

In this blog series we will deliver a strategy you can use to start adopting HTML5 today. We’ll break down the strategy into the following posts:

  • Part 1: Simplified Syntax & Semantic Elements
  • Part 2: Form Enhancements
  • Part 3: Local & Session Storage:

Client storage is no longer part of the HTML5 specification. Nevertheless we’ve decided to cover client storage as it is still popular as a topic in HTML5 discussions and is implemented in many of the modern browsers.

  • Part 4: Video & Audio Elements

Javascript Parameter Patterns with $.extend and Beyond

Enterprise developers have a tendency to misunderstand JavaScript’s function parameters. When getting started, many expect JavaScript functions to work much like the server-side languages they’re already familiar with. There can then be a fair bit of confusion when they find out things work a little differently with JavaScript.

The languages generally used on the server-side of enterprise development have static typing. The number and type of each parameter must be declared. In contrast JavaScript is considered a language with dynamic typing. JavaScript parameters do not have to be tied to a specific type at compile time. Additionally server-side languages do not include any of the ‘free’ parameters we get in JavaScript (more discussion on these parameters below).

A great example of the gap between common server-side languages and JavaScript is the .each method. To use this method you supply a function which will be executed against each element within the jQuery wrapped collection.

My first encounter with .each was similar to this:

//...
// note: this example is archaic as of 1.4 release
// please use function callback with .text instead!
$('.someClass').each(function() {
  var $this = $(this);
  $this.text($this.text() + " some extra text");
});
//...
$('.someClass').each(function(idx,val) {
  if(!(idx % 3)) { //modulus : will be true
                        //on every third element
    $(val).somejQueryMethod();
  }
});
//...

JS Bin demo

Create Your First jQuery Plugin Part 2:
Plugin Enhancements with .queue and .trigger

Note: This is part two in a two part series on creating your first plugin. You can find part one here. In the series we’re creating a plugin to handle displaying, and also queuing a series of a messages.

Plugin Enhancements

The plugin we worked on in Part 1 focused on getting from a simple jQuery snippet to a reusable and scalable plugin. This post will give us an opportunity to look at two popular techniques that can be used in a variety of situations. We’ll introduce these techniques by adding two enhancements to our code. We will enable the queueing of messages for the message center, and will add features to automatically close the message after a certain time period.

Utilizing jQuery Queues

jQuery queues provide an explicit mechanism for running synchronous operations anywhere they might be necessary. Our current plugin is a great fit for queues. If a previous message is being displayed we would prefer that the new message be queued and displayed synchronously afterwards.

The queue portion of the API contains two methods that are used most of the time. .queue is utilized to add items to the queue. It can also be used to determine the number of items currently in a given queue. .dequeue is used to kick off our queue, or at any point move to the next callback in the queue.

Mock Your Ajax Requests with Mockjax for Rapid Development

Most backend developers are familiar with the concepts of mocking objects or stubbing in methods for unit testing. For those not familiar with mocking, it’s the simulation of an interface or API for testing or integration development purposes. Mocking with front-end development though is still quite new.

Much of the development that appendTo does focuses on front-end development tied to RESTFUL web services. As such we’re able to spec out the service contract and data format at the beginning of a project and develop the front-end interface against mock data while the back end team builds the production services.

I originally developed this plugin for appendTo back in March of this year and our team has been using it in all of our projects since. appendTo is committed to sharing our tools and best practices with the community so it’s with much excitement that we’re releasing this plugin. (A sneak peek was available to the Silicon Valley JavaScript Users Group and those that attended our OSCON tutorial)

Plugin Overview

Abstract: The mockjax plugin is a development and testing tool for intercepting and simulating ajax requests made with jQuery with a minimal impact on changes to production code.

Configuring UI widgets and interactions with .live() and .delegate()

Configuring jQuery UI widgets often means making sure certain methods are called on a given DOM element (wrapped in jQuery) before usage occurs. We see this configuration pattern everywhere in jQuery UI. Great everyday examples include configuring the datepicker widgets, as well as draggable and droppable interactions. A relatively common example is something like the following:

$(function(){
  $('input.date:text').datepicker();
  //...
});