Content to JSON…
http://particletree.com/features/loading-content-with-json/
http://www.dustindiaz.com/json-for-the-masses/
JSON for the masses
<!– p class=’file’>Filed under: Accessibility , D.O.M. , Featured , JavaScript , PHP , Web Standards</p –>
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 back and 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 graduated
here. 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 unpopularity for 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 : value
pairs 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 c are 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 pair is 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 localhost and 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.js file 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 members of 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, doThat and tweakThis are all part of the behavior object. And runThat, wrapThis, stringifyThat and calculateThis are 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
this
is 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 this inside 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 this keyword in Object structures. Always take special note on where you’re calling this from. 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 alerter is being run from both an eventListener, and from the run method. 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!










Et bien d’autres outils plus dédiés au suivi de 


