About the Author:

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

May 25th, 2017
This is the first post in a multi-part series covering common mistakes C# developers tend to make when they first start learning 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.

(more…)

About the Author:

How to Clear an Array in JavaScript

February 2nd, 2016

Arrays are awesome! They allow you to store multiple values in a convenient, indexed set. In JavaScript, arrays can be declared literally or they can be initialized using the Array constructor function. But wait… What if you want to empty an array instead of creating one? Hmm… perhaps not as straightforward. Have no fear, there are some relatively easy ways to go about emptying an array in JavaScript. In the following examples, I’ll examine three different ways in which you can clear an array. I’ll then present some quirkiness related to one of the methods, as well as how to address it.
Here’s our example array:

var arr = [1, 2, 3, 4, 5];
console.log(arr); //[1, 2, 3, 4, 5]

https://codepen.io/anon/pen/adjwde?editors=0012
*Note here, that our array could be populated with any type of data, not just numbers.
Now, to clear it
Method 1
This method couldn’t be simpler; just set the value of the array in question to an clear array.

var arr = [1, 2, 3, 4, 5];
arr = [];
console.log(arr); //[]

https://codepen.io/anon/pen/ZQjyWw?editors=0012
Method 2
This method for emptying an array uses a for loop (could be any kind of loop) and the Array.prototype.pop() method.

var arr = [1, 2, 3, 4, 5];
for (var i = arr.length; i > 0; i--) {
 arr.pop();
}
console.log(arr); //[]

https://codepen.io/anon/pen/VeBWjj?editors=0012
Method 3
This third method is perhaps less intuitive, however, it’s as simple as the first and actually produces a more robust result. Simply set the length of the array to 0.

var arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr) //[]

https://codepen.io/anon/pen/GoBENm?editors=0012
Piece of cake! Three methods for clearing/emptying an array in JavaScript. Hold on… What was that quirkiness I was talking about earlier? Let’s have a look…
Method 1 is easy; just set the array to an clear array. However, you should be aware of the fact that setting an array equal to an empty one doesn’t affect all of the references to that array. Here’s what I mean….

var arr = [1, 2, 3, 4, 5];
var arr2 = arr;

Empty out the original array and…

arr = [];
console.log(arr); //[]
console.log(arr2); //[1, 2, 3, 4, 5]

https://codepen.io/anon/pen/adjwpb?editors=0012
Whoops! Emptying the original array by setting it equal to an empty array cleared it out, but it didn’t clear a reference to it. This could cause some issues! Methods 2 and 3 take care of the problem:

var arr = [1, 2, 3, 4, 5];
var arr2 = arr;
for (var i = arr.length; i > 0; i--) {
 arr.pop();
}
console.log(arr); //[]
console.log(arr2); //[]

https://codepen.io/anon/pen/WrKORy?editors=0012
and

var arr = [1, 2, 3, 4, 5];
var arr2 = arr;
arr.length = 0;
console.log(arr); //[]
console.log(arr2); //[]

https://codepen.io/anon/pen/ZQjyLP?editors=0012
As you can see, Methods 2 and 3 address the matter; emptying out the array and references to it. As to the question of which is the preferred method, there is a debate. Some claim performance is worse with Method 3 (discussion here). And some claim that readability is lost with Method 3. Still others don’t see these issues as drawbacks and prefer the simple elegance of writing length = 0.
Regardless of the pros and cons associated with each of the aforementioned methods, you now know three distinct ways in which you can empty an array in JavaScript. Additionally, you are now aware of a quirk associated with of one of the methods.
Use what you’ve learned. Go forth and clear those arrays!

About the Author:

jQuery Ajax and JSON Envelopes

March 28th, 2015

This is post 3 in a series on creating a JavaScript component for handling your Ajax requests in front-end development across your enterprise. You can find all the other posts here:

In the last post we covered using the publish/subscribe pattern along with some error handling code to add some loosely coupled error messaging and load notifications. We ended with the following code for the component:

var mySiteAjax = ( function( $ ) {
var standardError = "Oops. Sorry about that. Please try again.";

return {
getViaAjax: function( params ) {
var settings = $.extend({
url: '',
spinner: undefined,
dataType: 'html',
cache: false,
success: function(){}
}, params);

var retries = 0;
function ajaxRequest ( ) {
$.ajax({
beforeSend: function(){
$(document).trigger( "ui-load-start.message",
[{ spinner: settings.spinner }] );
},
url: settings.url,
dataType: settings.dataType,
success: settings.success,
complete: function(){
$(document).trigger( "ui-load-end.message",
[{ spinner: settings.spinner }] );
},
error: function( xhr, tStatus, err ) {
if( xhr.Status === "401" || xhr.Status === "403" ) {
//redirect action here
} else if ( xhr.Status === "504" && !retries++ ) {
ajaxRequest();
}
$(document).trigger( "ui-flash.message",
[{ message: standardError }] );
} // end error handler
}); // end $.ajax()
}; // end ajaxRequest()
ajaxRequest();
} // end getViaAjax()
}; // end return statement
})(jQuery);

In this post we are going to take this code and add on some explicit functionality for handling a JSON envelope.

## What is a JSON Envelope
A JSON envelope is a wrapper around JSON returning from the server. The wrapper serves to communicate any failures or messages back to the client along with the appropriate data if the request succeeded.

Consider a scenario where you are sending the server a few parameters and hope to receive a JSON structure back. What happens if you were to send a parameter which was invalid? The server would not be able to respond with the appropriate data and a failure should be communicated.

This is different from an HTTP status code as we were able to communicate with the server successfully. We need a solution to communicate any issues which may have occurred in the server code providing a successful response to our request.

A JSON envelope is a simple mechanism to communicate messages and failures to the client as part of a JSON response. Typically the intended data for the client is wrapped in an object. The JSON object sent back to the client includes this wrapped data if successful. If not the object sent back includes a message. In all cases the response object contains a status indicator.

A typical successful JSON enveloped response might look like this:

{
"status": "ok",
"data": {
"myData": "someData"
}
}

An error response contains a status property as well as a message property indicating the issue:

{
"status": "fail",
"message": "You did not supply the correct input data."
}

Another advantage of using a JSON envelope is that the object wrapper will alleviate a subtle JSON vulnerability (outlined [here](https://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) by Phil Haack).

### JSON Envelopes in use today

Many public services are implementing JSON envelopes for simple messages and error communication. The [Flickr API](https://www.flickr.com/services/api/) has a JSON envelope in place for simple communication of failures. You can find more information on the [JSON response format](https://www.flickr.com/services/api/response.json.html) page as well as example of [success](https://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=560f2f65e11cef441ba757d2b509b157) and [failure](https://www.flickr.com/services/rest/?method=flickr.blogs.getList&format=json&api_key=560f2f65e11cef441ba757d2b509b157) responses.

## Handling a JSON Envelope

Our first step is to handle the JSON envelope in our Ajax utility component and take action if a failure occurred. If the envelope indicates a successful response we need to invoke the success callback. As a reminder from last post `settings.success` is the success callback provider by the calling code (or an empty function if none was provided):

var mySiteAjax = ( function( $ ) {
//..
$.ajax({
//...
success: function(wrapper, tStatus, xhr) {
if(!settings.type.match(/^json/i)) {
return settings.success.call( this, wrapper,
tStatus, xhr);
if(wrapper.status === "success") {
return settings.success.call( this, wrapper.data,
tStatus, xhr);
}
$(document).trigger( "ui-flash.message",
[{message: wrapper.message}] );
},
//...
});
//...
})(jQuery);

We have created a success function callback that will be run when the response returns from the server. We will inspect the envelope for a status and will take action if the status is not successful. If it is a success, we will call the success callback provided in our settings.

The code snippet `return settings.success.call( this, wrapper, tStatus, xhr);` is particularly interesting. This may be the first time you have seen the `functionName.call()` method in JavaScript. This method allows us to set the context of the `this` argument in the function call. We could have done the following:

//...
if(wrapper.status === "success") {
setting.success(wrapper.data, tStatus, xhr);
}
//...

But what is the context of `this` in that case? Probably not what the `settings.success` callback would expect. If instead we use the `functionName.call()` JavaScript function we can set the context of `this` as well as all the other arguments for the function call. This allows us to precisely supply the context expected by the `settings.success` function.

To handle the error message we added the following action:

//...
$(document).trigger( "ui-flash.message",
[{message: wrapper.message}] );
//...

We are “publishing” by using jQuery events with a custom event name. Our “message topic” indicates that there is information that should be shared with the user. It is up to another component on our page to have subscribed to this topic and to take the appropriate action. We do not have to care if the message is actually published to the user, or how it is done. We have achieved separation of concerns. Doesn’t it feel nice?

## Handling different JSON Envelopes
Different JSON envelope implementations mean different JavaScript properties and success/failure statuses to deal with. Some sites may not have a JSON envelope. Our utility component needs to handle all these cases.

To do this we will add global settings. This will allow the user to set global defaults while using arguments specified to `mySiteAjax()` if a specific call involves a different JSON envelope.

To handle global setting we will add a settings property onto our mySiteAjax object. The code snippet below is long, but bear with me. We will break it down below.

var mySiteAjax = ( function( $ ) {
var standardError = "Oops. Sorry about that. Please try again.";

// create new Ajax utility as a "private" variable
var myAjax = function( params ) {

// add together global settings with arguments
var params = $.extend({},
myAjax.settings, params);

var retries = 0;

function ajaxRequest ( ) {

$.ajax({
// publish "local" loading start message
beforeSend: function(){
$(document).trigger( "ui-load-start.message",
[{ spinner: params.spinner }] );
},
type: params.type,
url: params.url,
data: params.data,
dataType: params.dataType,
success: function(wrapper, tStatus, xhr) {

// if json is the data type and the json wrapper exists
if( (/^json/i).test(params.dataType)
&& params.env.hasEnv) {
if(wrapper[params.env.statName]
=== params.env.successInd) {

// since wrapper indicated a success,
// call original success callback with the
// unwrapped JSON contents
return params.success.call( this,
wrapper[params.env.dataName],
tStatus, xhr);
}

// success wasn't indicated, publish
// message
$(document).trigger( "ui-flash.message",
[{message: wrapper[params.env.msgName]} ] );
} else {

// return unwrapped if response wasn't json or no envelope
// was specified
return params.success.call( this, wrapper,
tStatus, xhr);
}

},

// publish "local" loading end message
complete: function(){
$(document).trigger( "ui-load-end.message",
[{ spinner: params.spinner }] );
},
error: function( xhr, tStatus, err ) {
if( xhr.Status === "401" || xhr.Status === "403" ) {
//redirect action here
} else if ( xhr.Status === "504" && !retries++ ) {
ajaxRequest();
}
$(document).trigger( "ui-flash.message",
[{ message: standardError }] );
} // end error handler
}); // end $.ajax()
}; // end ajaxRequest()
ajaxRequest();
};

// settings which are global and attached
// to the myAjax function as a property
myAjax.settings = {
url: "",
spinner: undefined,
dataType: "json",
cache: false,
type: "GET",
success: function(){},
env: {
hasEnv: true,
statName: "status",
successInd: "success",
dataName: "data",
msgName: "message"
}
};

//returns the newly created function with the properties attached.
return myAjax;

})(jQuery);

You’ll notice we moved around things. The function is now specified as a named function (although the scope is still within our component code only). We’ve also moved our settings to a property of our main utility function. Since JavaScript functions are objects augmenting it with properties is valid. You’ll also notice that we have an empty object literal as the first parameter to `$.extend()`. This is because the extend method will merge all of the object together and replace the first object with the merged results. We do not want to overwrite our global setting object each time!

Exposing our settings as a property gives us a clean way to specify defaults for a specific page. For example we can set the default HTTP action to POST with minimal effort:

myAjax.setting.type = "POST";

We’ve added settings for the JavaScript envelope. With our settings we can determine whether or not an envelope is used and how to leverage the envelope. Turning off the envelope functionality is now a one line setting:

myAjax.setting.env.hasEnv = false;

In our wrapper code we have changed the way we access objects. For example there is now this snippet:

//...
if( wrapper[params.env.statName]
=== params.env.successInd ) {
//...

Remember that we can access object properties through dot notation or bracket notation. Bracket notation allows you to specify the name of the property as a string. In our above example, with our default global setting of “success” as our status name, the code would evaluate to `wrapper[“success”]`. This would access the success property of the wrapper object. So using this piece of functionality we do not even need to know the names of the properties of our JSON object until runtime!

We now have a working Ajax Utility Component which includes a JSON envelope! I’ve set up a few examples and a playground for the component as a [jsFiddle](https://jsfiddle.net/YLKUz/1/). Please play around and ask questions in the comments!

About the Author:

Replacing Common UI Icons with CSS

March 11th, 2014

Let’s be honest, dealing with images on the web is kind of a pain. They’re a pain to modify, load slowly and require all sorts of progressive techniques in a responsive environment. But, unfortunately, images are here to stay; there’s no better way to capture a moment in time than with an image. However, we can significantly reduce our use of images by using CSS to recreate elements. But how can we do this while still keeping our designs visually appealing?

With our powers combined

Modern browser technology is our best friend, namely the technology of CSS with its shape rendering capabilities. We can do some crazy stuff with CSS alone! So in this article, we’re going to start simple and see how we can replace common user interface icons with just CSS. No more loading custom icon fonts or exporting PNGs.

Explore CSS Courses

Let’s jump right in

We’re going to go through the creation of 5 fairly standard UI icons:

Hamburger icon

Mail icon

Heart icon

Home icon

Camera icon

I’ve chosen these mainly because they can be easily created with little code and with only one element.

A quick note on browser support: anytime I use the border-radius or transform properties, I’m not prefixing them with vendor prefixes, so you may want to add their proper prefixes for wider browser support. Also, all of the examples below work in all modern browsers, including IE9.

Hamburger icon

We see this hamburger-looking icon a lot in mobile navigation patterns. It’s a very simple one to create with CSS, as it’s just 3 rows with some space in between.

The markup for all of these icons will be the same. We’ll use the i element with a reusable icon class and a unique identifier class, like icon_hamburger.




.icon {
  position: relative;
  display: inline-block;
}

.icon::before,
.icon::after {
  content: "";
  position: absolute;
}

Notice I created rules for the ::before and ::after pseudo-elements and set the content property to an empty string and positioned them absolutely. We’ll be relying heavily on these pseudo-elements to get the job done (hence why we can create these icons with only one HTML element).

For the hamburger icon, we’ll start off by giving .icon_hamburger a width, height and background.

.icon_hamburger {
  width: 1.625em;
  height: .313em;
  background: black;
}

Hamburger icon step 1

Now to add in the top and bottom lines. We’ll use ::before for the top line and ::after for the bottom.

.icon_hamburger::before,
.icon_hamburger::after {
  width: 1.625em;
  height: .313em;
  background: black;
}

.icon_hamburger::before {
  top: -.625em;
}

.icon_hamburger::after {
  bottom: -.625em;
}

Hamburger icon step 2

That’s it! It’s so much easier than an image to maintain, too. Want to change the width? Just modify the pixel value; no Photoshop required! Want to change the color? Easy!

[cta id=”3126″ align=”none”]

Mail icon

The mail icon (envelope) is another item commonly seen in many UIs. To start out, we’ll set the borders to create a rectangle with a triangle notched out of the top. Joel Glovier wrote a great article a while ago on the appendTo blog explaining how CSS triangles work.

.icon_mail {
  border-top: 1.063em solid transparent;
  border-right: 1.25em solid black;
  border-bottom: .5em solid black;
  border-left: 1.25em solid black;
}

Mail icon step 1

Then to create the envelope flap, we’ll use the same technique again to create a triangle with a negative top and left value. The negative top value offsets it from the top just enough to provide the space between the flap and the actual envelope.

.icon_mail::before {
  top: -1.25em;
  left: -1.25em;
  border-top: 1.063em solid black;
  border-right: 1.25em solid transparent;
  border-left: 1.25em solid transparent;
}

Mail icon

Heart icon

Creating the heart shape involves rotating the pseudo-elements with the transform property, and applying a large border-radius to the top of each tilted rectangle. The main element itself needs no properties at all. First, we’ll create two rectangles out of our ::before and ::after pseudo-elements.

.icon_heart::before,
.icon_heart::after {
  width: 1em;
  height: 1.563em;
  background: black;
}

.icon_heart::after {
  left: .375em;
}

Heart icon step 1

Then we’ll rotate them.

.icon_heart::before,
.icon_heart::after {
  width: 1em;
  height: 1.563em;
  background: black;
}

.icon_heart::before {
  transform: rotate(135deg);
}

.icon_heart::after {
  left: .375em;
  transform: rotate(45deg);
}

Heart icon step 2

And lastly, add a border-bottom-radius to the ::before pseudo-element (because it’s rotated upside down) and a border-top-radius to the ::after.

.icon_heart::before {
  transform: rotate(135deg);
  border-bottom-radius: .5em;
}

.icon_heart::after {
  left: .375em;
  transform: rotate(45deg);
  border-top-radius: .5em;
}

Heart icon step 3

Home icon

Creating a home icon starts out by morphing the main element into a triangle.

.icon_home {
  border-bottom: .938em solid black;
  border-left: .938em solid transparent;
  border-right: .938em solid transparent;
}

Home icon step 1

Then we’ll just create two vertical rectangles below the triangle and space them apart to give the impression of a door in the middle.

.icon_home::before {
  width: .563em;
  height: .625em;
  background: black;
}

.icon_home::before {
  margin: .938em 0 0 -.688em;
}

.icon_home::after {
  margin: .938em 0 0 .125em;
}

Home icon step 2

Camera icon

The camera icon, like the mail icon, starts out as a rectangle with a small border-radius.

.icon_camera {
  width: 1.938em;
  height: 1.375em;
  margin-top: .813em;
  background: black;
  border-radius: .125em;
}

Camera icon step 1

Then we’ll use the ::before pseudo-element to create a flash on top of the camera, in the shape of a trapezoid. The trapezoid shape is defined similarly to the way we create triangles, except we need to add a width.

.icon_camera::before {
  height: 0;
  width: .938em;
  margin: -.313em 0 0 .313em;
  border-bottom: .313em solid black;
  border-left: .188em solid transparent;
  border-right: .188em solid transparent;
}

Camera icon step 2

And finally we’ll add the lens to the front of the camera, using a circle with a border.

Explore CSS Courses

.icon_camera::after {
  width: .438em;
  height: .438em;
  margin: .125em 0 0 .5em;
  border: .25em solid white;
  border-radius: .438em;
}

Camera icon step 3

Taking it further

As you hopefully saw, creating CSS icons is really not that difficult and doesn’t require a ton of code. I’ve created a CodePen with all of these icons plus a few more. Feel free to play around with it!

Browser support

As mentioned above, all of these examples work in all modern browsers, including IE9. Some of the new CSS3 properties require vendor prefixes, so make sure you use the proper prefixes. In my CodePen, I’m using Compass @includes, which automatically adds in the proper vendor prefixes. If your project requires IE8 support, you unfortunately might want to rethink the use of solely CSS icons, or at least stay away from icons that require border-radius and transform. My suggestion for a fallback would be to use Modernizr to detect which browsers don’t support border-radius and transform, and provide a background image as a fallback.

Explore CSS Courses

About the Author:

EdisonJS – Organized Routing for Complex Single-Page Applications

February 11th, 2014

Over the past few years, “single-page applications” have steadily grown in popularity within the web development industry. As developers have grown accustomed to placing the bulk of the responsibility for rendering these “thick client” apps within the browser, new libraries that provide repeatable patterns for solving frequently encountered issues when using a client-heavy approach have flourished. Chief among these new libraries – JavaScript routers.

(more…)

About the Author:

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

October 21st, 2010

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.

(more…)

About the Author:

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

October 13th, 2010

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.

(more…)

About the Author:

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

October 7th, 2010
This is the first post in a multi-part series covering common mistakes C# developers tend to make when they first start learning 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.

(more…)

About the Author:

Creating an Ajax Component:Handling Errors and Loading Notifications with Publish and Subscribe

September 28th, 2010
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?

(more…)

About the Author:

Javascript Parameter Patterns with $.extend and Beyond

August 12th, 2010

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).

[cta id=”3166″ align=”none”]

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

(more…)