From:

JSON for the masses

Your co-workers will love you for writing in JSON because it will most likely not conflict with their scripts that are being called within the same web documents.

For Many Years…

JavaScript has been portrayed as a very ugly language. It’s been abused, misunderstood, and kicked around like the poor step-child as known in fairytales. That’s all going to end this year. As many know, Stuart Langridge proclaimed that 2005 would be the year of the DOM. He was in fact…correct. 2006 will be the year of Object Notation.

Libraries like prototype, script.aculo.us, behavior, and Rico have all made their debut in 2005 and topping the charts of development circles as some of the greatest things to happen for web developers. JavaScript is backand it’s cooler than ever! Web 2.0 is in the air (whatever that means) and innovation is at its peak (Hey, even Zeldman says we’re at web 3.0). Anyone with a D.O.M. wants to script it too. It’s in, it’s popular, and it’s only getting better.

Why?

Because JSON is here. And not only is it here, but it’s been to college and graduatedhere. Being part of the ECMA Standard of 1999, and then popularized by Douglas Crockford in 2002 (sort of), Object Notation has quite a history. And although that history has been ignored for quite some time, that does not excuse its unpopularityfor so many years. It’s time to get with it and develop your JavaScript in Object Notation.

Reasons for JSON

  • JSON is easy. No really. It’s so easy, it’ll make you sick.
  • If you’re familiar with writing classes in PHP, then you’ll most definitely be comfortable with writing JavaScript in Object Notation
  • JSON is nothing more than name : valuepairs assigned within an object.
  • JSON is easy to understand because if written well, it’s a self-documenting structure.
  • JSON is fast!
  • JSON organizes the ugly mess of procedural programming. Imagine having more than one initfunction.
  • You can impress your friends with JSON because it’s pretty looking
  • Your co-workers will love you for writing in JSON because it will most likely not conflict with their scripts that are being called within the same web documents.

No more fuss of writing function after function that has no meaning to which other group of functions it belongs to

What is Object Notation in JavaScript?

According to Douglas Corckford’s website, JSON is a lightweight data-interchange format. It is easy for humans to read and write… JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

As a simple example, Object Notation can be expressed in the following format:

Sample Object Notation Reference

var obj = {
	// string
	a : 'sampleValue',
	// array
	b : [obj1,obj2,'three',4,obj5],
	// function
	c : function() {
		var bang = this.a;
	}
}

In the above example, a, b, and care the names, and their values are expressed immediately following the colon up until the following name (excluding the final value - in which the value just goes until the end of the object). Each pairis considered a member.

Names

Names can be anything except one of the JavaScript reserved keywords - which come to find out can actually be quite lengthy. Names also follow a few syntax rules which include not being allowed to start with a number; the entire name may not include any special characters except an underscore or dollar sign; and it cannot be a duplicate of a previously used name within the same object.

Values

Values can be expressed as a string, number, object, array, boolean (true,false), or null. To see a full explanation of the syntax rules, see Douglas’ JSON Website.

So what’s the good news?

Part of the reason JSON is so easy is that it is easy to read(for humans and programs (think parsing)). No more fuss of writing function after function that has no meaning to which other group of functions it belongs to. The fact of the matter is that programming with objects allows you as a developer to separate functions into subsets that will allow you to organize your scripts that won’t clash with one another. And although the big hoo-haa on JSON right now is that it’s a light-weight data-exchange format that multiple languages can easily understand - it simply makes sense just to use it on a structual level - even if you aren’t exchanging data.

programming with objects allows you as a developer to separate functions into subsets that will allow you to organize your scripts that won’t clash with one another

Object Notation will improve your health

If anyone has read anything by Sitepoint’s Harry Fuecks, you’ll know that Object Oriented Programming will save your life. It keeps the hair on your head and a sane mind to live in harmony with other people of this earth. It just makes sense. So if anything, take his word for it, this is where you want to be.

Better Organization

Imagine this. You’ve been asked to help out on a relatively large-scale web development project to help make it “web 2.0″ compliant (sounds cheezy, but let’s not give the marketing department too many more ideas). The project has already been worked on for roughly a month as a few things have already been written and done. The website architecture is laid out before and you quickly notice a few lines of JavaScript. Turns out it’s just some pop-up window function. No big deal. You also notice a few more lines that add a few functions to be fired upon the window ‘load’ event. With that in mind you scroll a bit back up the document and also find a few references to some external JavaScript files located appropriately in the /js/directory. One called common.js, another preferences.js, and yet another effects.js.

At this point you begin to sulk into your chair just knowing that you’re going to be spending the day just figuring out what’s going here. Not exactly an ideal situation. Also keep in mind that nobody is aware of the benefits of writing in Object Notation. So this is going to get tedious real fast.

Getting back to the story, your task according your project manager (whomever that may be) is to add some behavior to the sidebar, something fancy, and then maybe spruce up the navigation menu with some indicators…or something like that (you’re not really sure). Brushing off what you may have found earlier, you decide to fire up a new document and call it scripts.js, then immidiately you begin hacking away to fulfill your duty as a web 2.0 developer (someone bring me back to reality when this is over).

Come Runtime, Problems arise

The day goes by and you’re satisified with your newly developed set of functions. It was all tested on localhostand works to a tee. In other words, it’s perfect.

The next day you decide it’s time to implement your new set of functions into the existing web documents… and that’s when it happens.

It turns out you’re not the only one that likes to use function names like init, run, and wrap. Without a doubt, I too have the InitRunWrap fever- so you’re not alone.

A 2006 Proposal

The following graph is a representation of what the typical common.jsfile looks like.

Albeit the confusion between objects and global variables, the distinction between the two should be that variables will now sit within the objects to which they pertain to. This is called scoping.

How scoping helps us

For anyone familiar with other O.O. languages - like Java or PHP, you may already be familiar with scoping. Scoping allows us to avoid clashing. Previously in our brief story about the JavaScript developer that named his/her functions with name’s like init, run, and wrap, this could have all been avoided had the previous developer scoped their functions within their own objects. If that had happened, then all we would have to worry about is not to use the same object name’s… which would probably be far more easier to avoid.

JSON is easier to read, maintain, and provides better organization

Functional vs Classy

When I’m writing JavaScript, I typically like to think that there’s two ways I can go about developing. Functional, and Classy. Functional being the standard procedure we’ve been doing for years, and Classy being that of which is written in Object Notation. And although both will get the job done - I tend to go for the classy route not only because I like to show off, but because it’s easier to read, maintain, and provides better organization.

Functional works

There’s nothing wrong it. Even some of the greatest developers in the world still do it. But there’s something inherently wrong with it. Let’s take for example a make-believe JavaScript behavior that requires use of more than a handful of functions.

Related Group of Functions

var a = '';
var b = null;
var c = document.getElementById('c');
function init() {
	// ...
}
function doThis() {
	// ...
}
function doThat() {
	// ...
}
function tweakThis() {
	// ...
}
function runThat() {
	// ...
}
function wrapThis() {
	// ...
}
function stringifyThat() {
	// ...
}
function calculateThis() {
	// ...
}
window.onload = init;

(On Functional Programming) The role of a function becomes globalized and yet becomes vague as to what its purpose is. Give it scope, then we’re in business

No doubt we can fill in the gaps as to what this possibly might mean. The problem is that this may be okay for some small project where you’re the developer and the boss, but for any project of a respectably large size, you’ll find out that this is going to cause problems fast.

And not only that, but think of the issues that will arise when you want to add extra behavior on top of this. Not only can name’s begin to clash, but it will get confusing as to what function’s belong to which group. The role of a function becomes globalized and yet becomes vague as to what its purpose is. Give it scope, then we’re in business

JSON: A Class Action

Let’s rewrite our make-believe functions into Object Notation and compare the differences.

Grouping Functions in an Object

var behavior = {
	a : '',
	b : null,
	c : Object,
	init : function() {
		// ...
		this.c = document.getElementById('c');
	},
	doThis : function() {
		// ...
	},
	doThat : function() {
		// ...
	},
	tweakThis : function() {
		// ...
	}
}
var behavior2 = {
	runThat : function() {
		// ...
	},
	wrapThis : function() {
		// ...
	},
	stringifyThat : function() {
		// ...
	},
	calculateThis : function() {
		// ...
	}
}

As you might be able to tell, we’ve now given our set of variables and functions scope! The greatest part about this was that it was so easy. By giving our set of functions a name (behavior & behavior2) and swapping our function name’s into name/value pairs which become membersof their parent objects, we’ve now experienced the beauty of Object Notation.

You may also notice its terrible resemblance of PHP classes where behavior and behavior2 are classes, and the functions within them are the methods respectibly

The Noticable Differences

First of all, had we not rewritten these set of functions into methods of objects, you may have never known that they were in fact, two different sets of behaviors meant for something completely different from one another. For example, init, doThis, doThatand tweakThisare all part of the behaviorobject. And runThat, wrapThis, stringifyThatand calculateThisare part of the behavior2 object. Both of which may very well be doing two very different things. With that in mind, we can see now that global functionalism(yea, I made that up) is bad.

Another difference we may see is that we have now gained the pleasures and benefits of Object Oriented structures. And by that, I mean this

Low and behold: The power of this

thisis a keyword often used in Object Oriented languages that help generify (now I’m just making words) naming conventions. In the cases of both behavior objects, if we were to reference thisinside any one of its child methods, it would be corresponding to its most outer parent object.

For instance, in the behavior object, the first three members are set to an empty string, null, and Object. Inside the init()method, we had set the member ‘c’ by referencing it as this.c. And from that point on, we can continue to reference ‘c’ throughout the entire object simply by using the keyword this. Really, it’s that simple.

Careful how you use this

Just when you think you’ve got things down, there’s only one caveat that often goes overlooked when using the thiskeyword in Object structures. Always take special note on where you’re calling thisfrom. Consider the following piece of code:

Carefulness with this

var jack = {
	a : Object,
	init : function() {
		this.a = document.getElementById('jane');
		this.a.addEventListener('click',this.alerter,false);
		this.run();
	},
	run : function() {
		this.alerter();
	},
	alerter : function() {
		alert(this.id);
	}
}
function pageLoader() {
	jack.init();
}
window.addEventListener('load',pageLoader,false);

If you take special notice, you’ll see the method alerteris being run from both an eventListener, and from the runmethod. If you were to access a page with this code on it, you would see an alert upon the window ‘load’ event that would read as ‘ undefined‘ - but when fired upon the ‘click’ event from a link with the id of ‘jane’, we would indeed see an alert that read as ‘jane‘.

An Object Template

When developing new scripts, I often like to refer to a forumla that helps me stay organized and keep my code clean. Aside from it being unobtrusive(as coined by Stuart Langridge in Sitepoint’s DHTML Utopia) it’s what I call an Object Template. No, Object templates aren’t real things and they surely aren’t part of the D.O.M., but it is more or less of a way of creating a generic Object set up that will hold my page architecture. It looks like this:

My Object Template

var obj = {
	a : Object,
	b : Array,
	c : false,
	d : null,
	init : function() {
		// set local object vars here
		this.run();
	},
	run : function() {
		// run bulk of behavior here
	}
}
function initializer() {
	obj.init();
	// other init() methods go here
}
addEvent(window,'load',inializer);

Assuming you have an addEvent()function handy, this is a simple way to get things started. You’ll notice at the bottom the inializer which fires upon the window ‘load’ event which will in return fire any init()methods we have from different Objects. Then within the ‘obj’ Object literal, there’s a, b, c, and d which all represent possible values for these name value pairs.

The init() method itself I most typically like to use it to set up the object setting things like this.whatever, and then at the end, it runs the objects bulk of the behavior through the run() method.

Great what do I do with all this knowledge

Practice it. Learn it. Re-read it. Tell me what you think! JSON is not only for the pro’s, it’s for the masses!

Related Articles

Relatd Projects

JSJaC

JSJaC is a jabber/XMPP client library written in JavaScript to ease implementation of web based jabber/XMPP clients. For communication with a jabber server it needs to support either HTTP Pollingor XMPP Over BOSH(formerly known as HTTP Binding). JSJaC has an object oriented design which should be quite easy to use. Communication is done by using the XML HTTP Request objectalso refered to as AJAX technology. Your browser must support this.

XSTM

What is XSTM?


XSTM
is a n open sourcelibrary which enables high performance object replication between processes. It is an object oriented Distributed Shared Memory, or a Distributed Object Cache.

XSTMhas similarities with technologies like Adobe Flex Data Services , JBoss Cache, Terracotta, Tangosol Coherence , ScaleOut , or IBM's ObjectGrid .

Our model is based on object shares, which work like file shares. When an object is added to a share, it appears on the other machines which have the same share opened. Modifications done to the fields of the object are from this point replicated between machines.

Read more in the project overview.


XSTMis made of three projects. The Java implementation is called JSTMand is the base from which the other versions are derived. An adapted version made with Luciano, the author of GWM , is available for GWT . It allowsthis library to be used in a browser. NSTM is a .NET port based on IKVM.

All implementations are compatible with each other so object replication can take place e.g. between a Java server and a .NET Smart Client.

google caja

Using Caja, web apps can safely allow scripts in third party content.
The computer industry has only one significant success enabling documents to carry active content safely: scripts in web pages. Normal users regularly browse untrusted sites with Javascript turned on. Modulo browser bugs and phishing, they mostly remain safe. But even though web apps build on this success, they fail to provide its power. Web apps generally remove scripts from third party content, reducing content to passive data. Examples include webmail, groups, blogs, chat, docs and spreadsheets, wikis, and more.
Were scripts in an object-capability language, web apps could provide active content safely, simply, and flexibly. Surprisingly, this is possible within existing web standards. Caja represents our discovery that a subset of Javascript is an object-capability language

Facebook API

This JavaScript client library allows you to make Facebook API calls from any web site and makes it easy to create Ajax Facebook applications. Since the library does not require any server-side code on your server, you can now create a Facebook application that can be hosted on any web site that serves static HTML. An application that uses this client library should be registered as an iframe type. This applies to either iframe Facebook apps that users access through the Facebook web site or apps that users access directly on the app’s own web sites. Almost all Facebook APIs are supported.

script.aculo.us
script.aculo.us provides you with easy-to-use, cross-browser user interface JavaScript libraries to make your web sites and web applications fly.
AJAXInterceptor
Project Description
Just by adding this small JavaScript module to the end of your web pages, you get your form's submissions intercepted and, instead of sending request to the server in the usual way, they are done asynchronously and in an AJAX-style smooth way.

As long as it is a client-side library it will work with any server technology: ASP.NET, PHP, JSP, Classic ASP... and even with local HTM files.

I've included extensibility so that you can add easily your own progress indicators (several included) and show error messages the way you prefer (by default it shows an alert).

It's transparent to your server code and could be used to add AJAX capabilities to some applications without writting a single line of code.

Documentation is included.



Features summary

• No-code AJAXification of web apps
• Supports any server technology, including ASP.NET, JSP, PHP, ASP 3.0...
• In ASP.NET it supports all kinds of postbacks: direct and by code.
• Works in any modern browser that supports AJAX.
• Supports cross-posting of forms, that is, you can send the information to any web page in the same domain. If all your web pages have AJAXInterceptor included (for example, you include it in your master page or template) you can hace
• Respects your custom onsumit event handlers.
• Supports browser history so that your users can hit the previous button and get the last rendered page.
• Two versions of the module:
- AJAXInterceptor.js: full commented one. Useful for debugging purposes.
- AJAXINterceptor_r.js: reduced-size version. It downloads faster as it only is 2.6 kB in size. It's better to use this on production apps.
• Automatically show/hide custom progress indicators.
• Support for cancelling operations.
• Support for custom message displaying.
• Supports any form in your page

Obviously this is not substitute at all of full-fledged APIs like Microsoft's ASP.NET AJAX, PHPLiveX or AJAX.NET, but will let you add AJAX support to your apps in a few seconds and without writing any code. Just give it a try!

In the ZIP you will find teh module, a working sample with ASP.NET and a PDF with the help documentation.

This project is just for fun :-)

I will be very glad if you drop me a line in case you use AJAXInterceptor in any real-world application or if you enhance it with new features.

Visit my .NET blog (Spanish) at http://www.jasoft.organd my e-mail marketing blog (English) at http://www.theemailingexperience.com
newjs

A simple command-line tool to create the folders and helper files for a new JavaScript project/library. As a bonus, you can quickly create a website to promote your project.

When you start a new JavaScript library, how do you layout the source files, the tests, the distribution files? Do you have support scripts to generate distributions from source files? Run your JavaScript unit tests? Generators to create new unit test HTMLfiles?

mapper.js
mapper.js 1.2 allows you to add automatic area highlighting to image maps on your webpages (inc. export to SVG). It works in all the major browsers - Mozilla Firefox 1.5+, Opera 9+, Safari and IE6+. On older browsers, it can use "jsgraphics" from Walter Zorn (if installed), else it'll degrade and your visitors won't notice a thing.
Highslide JS
Highslide JS is an open source JavaScript software, offering a Web 2.0 approach to popup windows. It streamlines the use of thumbnail images and HTML popups on web pages. The library offers these features and advantages:
  • No plugins like Flash or Java required.
  • Popup blockers are no problem. The content expands within the active browser window.
  • Single click. After opening the image or HTML popup, the user can scroll further down or leave the page without closing it.
  • Compatibility and safe fallback. If the user has disabled JavaScript or is using an old browser, the browser redirects directly to the image itself or to a fallback HTML page.
GWT(Google Web Toolkit)

Google Web Toolkit (GWT) is an open source Java software development framework that makes writing AJAX applications like Google Mapsand Gmaileasy for developers who don't speak browser quirks as a second language. Writing dynamic web applications today is a tedious and error-prone process; you spend 90% of your time working around subtle incompatibilities between web browsers and platforms, and JavaScript's lack of modularity makes sharing, testing, and reusing AJAX components difficult and fragile.

GWT lets you avoid many of these headaches while offering your users the same dynamic, standards-compliant experience. You write your front end in the Javaprogramming language, and the GWT compiler converts your Java classes to browser-compliant JavaScript and HTML.