August 26, 2008 PLEASE FORWARD
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tips, Tricks, News and Reviews for Web Coders
by Kevin Yank (techtimes@sitepoint.com)
Read the HTML version of this newsletter, with graphics, at:
http://www.sitepoint.com/newsletter/viewissue.php?id=3&issue=204
Note: This newsletter is supported solely by advertisers like the
one below. We stand 100% behind every ad that we run. If you ever
have a problem with a company that advertises here please contact
us and we will try to get it resolved.
INTRODUCTION - - - - - - - - - - - - - - - - - - - - - - - - - -
Welcome to a bumper edition of the SitePoint Tech Times!
This week's guest writer is James Edwards, front-end wizard and
the author of the yet-to-be-released SitePoint JavaScript
Reference. In this edition, James writes about debugging
JavaScript and using JSON for configuration.
SPONSOR'S MESSAGE - - - - - - - - - - - - - - - - - - - - - - - -
* Do your site visitors enjoy a happy landing? *
Get more visitors and provide them with a better user experience w
ith Web CEO.
Web CEO is a full-fledged software solution to obtain a visitor
and search engine-friendly site.
- Optimize your site for high rankings
- Increase your site's link popularity
- Make your site error-free
- Understand your site visitors with 120 reports
12 tools + online SEO training. Download the Free Edition Now:
http://www.webceo.com/?source=SitepointDV
IN THIS ISSUE - - - - - - - - - - - - - - - - - - - - - - - - - -
- Introduction
- Debugging JavaScript: Throw Away Your Alerts!
- Using JSON for Language-independent Configuration Files
- New Technical Articles
- Techy Forum Threads
- More Techy Blog Entries
DEBUGGING JAVASCRIPT: THROW AWAY YOUR ALERTS! - - - - - - - - - -
One JavaScript statement that rarely surfaces in the wild is
throw(). The throw statement allows you to throw a formal error
-- sending details of the error to the browser's error
console -- and halting further execution of the script.
The throw statement is particularly useful for APIs developers,
as a way to warn its user-developers about runtime issues, such
as missing or invalid input data. Its use should be generally
preferable to alert() because it makes best use of the browser's
native functionality (and it's less annoying):
if(typeof input == 'undefined')
{
throw('Missing input');
}
else if(parseFloat(input) != input)
{
throw('Input must be a number');
}
Using throw() with a string argument will throw a general error.
However you can also create and pass an Error object, with which
you can specify more details about the error:
var err = new Error();
err.name = 'My API Input Error';
err.message = 'Input must be a number';
throw(err);
The example above produces this output in Opera's error console:
<http://www.sitepoint.com/blogs/wp-content/uploads/2008/08/throw-opera.gif>
Firefox's console doesn't show the error name, only the message;
but it's still almost as useful:
<http://www.sitepoint.com/blogs/wp-content/uploads/2008/08/throw-firefox.gif>
The important thing to note is that anywhere you use throw()
will halt the execution of the script (not just the enclosing
scope). So you should arrange your code so that any throw()
statement comes at the end of an execution block:
function err(type, message)
{
var err = new Error();
err.name = 'My API ' + type + ' Error';
err.message = message; throw(err);
}
// the delete in this example won't happen
if(typeof this.input == 'undefined')
{
err('Input', 'Missing input');
delete this.input;
}
// but this delete will happen fine
if(typeof this.input == 'undefined')
{
delete this.input;
err('Input', 'Missing input');
}
Of course, a single language statement -- however useful
-- can never replace a fully-featured debugging tool like
Firebug; a proper debugger lets you set breakpoints,
watchpoints, step-through execution ... all kinds of goodness.
Firebug even lets you log messages to its own console.
But Firebug is a browser-specific tool, where this is a
cross-browser language feature, so it can be safely integrated
into the heart of a script without any chance of unsatisfied
dependencies.
Add your comments to the blog entry:
Debugging JavaScript: Throw Away Your Alerts! [1]
by James Edwards
Web Tech Blog: Technically Speaking
[1] <http://www.sitepoint.com/blogs/2008/08/22/debugging-javascript-throw-away-your-alerts/>
SPONSOR'S MESSAGE - - - - - - - - - - - - - - - - - - - - - - - -
Maintaining a website can be both fun and sometimes frustrating
especially if the web host does not catch up to your needs. The
owners behind WebHostingBuzz have experienced it all.
We have been there and done it. We know what YOU want when it comes
to running a script oriented website. We know what YOU want when it
comes to value for your web hosting dollars. We host over 150,000
domains across the globe. Surely we can host yours!
Host unlimited websites under one account. Get a free domain name
for life, tons of web space and transfer for only $40 per year.
http://www.webhostingbuzz.com/website-hosting.shtml?host_sitepoint-special
USING JSON FOR LANGUAGE-INDEPENDENT CONFIGURATION FILES - - - - -
The growing availability of JSON parsing in server-side
frameworks elevates the usefulness of JavaScript beyond
client-side programming, to providing base syntax for a
generalized data interchange format. Well duh.
But a not-immediately-obvious advantage of this is the ability
to have language-independent configuration files for Ajax
development.
In a nutshell -- a JavaScript object-literal can be parsed
as JSON with (say) PHP to create a corresponding associative
array.
Consider a simple config object like this:
const config = {
'lang' : 'en',
'host' : 'sitepoint.com'
};
We can include that in a regular <script> and get access to its
properties with JavaScript:
alert(config['lang']); //outputs "en"
All good. But we can also import it into PHP and parse it like
this:
$datastring = file_get_contents('config.js');
$regexes = array(
// remove comments
array("p"=>"/[\w]*(\/\/).*$/m", "r"=>""),
// replace single-quotes with double-quotes
array("p"=>"/'/m", "r"=>"\"")
);
foreach($regexes as $regex)
{
$datastring = preg_replace($regex['p'], $regex['r'], $datastring);
}
preg_match("/config[ ]?=[ ]?\{([^\;]+)\\;/", $datastring, $matches);
$config = json_decode('{' . $matches[1], true);
And then we have that same data in a PHP associative array:
echo $config['lang']; //outputs "en"
AVAILABILITY OF JSON PARSING IN PHP
The native functions json_encode [1] and json_decode [2] were
not added to PHP until Version 5.2. If you're using an earlier
version you'll need to implement them yourself, and for this I'd
recommend Michal Migurski's JSON Services class [3]. The only
disadvantage of this is that it only supports conversion to an
object, not to an associative array (as triggered by the true
flag in the native functions).
However you can fix that with recursive object to array
conversion. Here's a litte snippet to do that; I didn't write
this, but I'm afraid I can't remember where I found it either:
function object_to_array($data)
{
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
Then you'll be able to do the original conversion like this:
$config = object_to_array(json_decode('{' . $matches[1]));
CONCLUSION
The advantage of this is obvious -- both the client-side
and server-side layers of an application can get their
configuration data from a single managed source.
Add your comments to the blog entry:
JavaScript & CSS Blog: Stylish Scripting
by James Edwards
Using JSON for Language-independent Configuration Files [4]
[1] <http://www.php.net/json_encode>
[2] <http://www.php.net/json_decode>
[3] <http://pear.php.net/pepr/pepr-proposal-show.php?id=198>
[4] <http://www.sitepoint.com/blogs/2008/08/21/using-json-for-language-independent-configuration-files/>
SPONSOR'S MESSAGE - - - - - - - - - - - - - - - - - - - - - - - -
Create and Deploy Rich Internet Applications on the Desktop with
Adobe(R) AIR(TM) software.
With Adobe AIR, Ajax developers can use existing skills and code to
build responsive, highly engaging applications that combine the power
of local resources and data with the reach of the web. Deliver
applications to the desktop that complement and expand your browser
applications.
Download the Adobe AIR SDK and Ajax docs to start building applications
today: http://ad.doubleclick.net/clk;205795763;28433742;q
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Hope you have enjoyed this issue -- thanks for reading! See you
next week.
Andrew Tetlaw
techtimes@sitepoint.com
SitePoint Technical Editor
NEW TECHNICAL ARTICLES - - - - - - - - - - - - - - - - - - - - -
Learn Adobe AIR, Part 1: Build A Note Storage App
by Akash Mehta
Following up from his competition-winning tutorial, Akash
explains how to use Adobe AIR to build a handy notes storage
app. This is the first of three articles on building web-enabled
desktop applications using the exciting Adobe AIR platform.
http://www.sitepoint.com/article/1665
TECHY FORUM THREADS - - - - - - - - - - - - - - - - - - - - - - -
Hacking Wordpress to reverse category archives?
<http://www.sitepoint.com/forums/showthread.php?threadid=567389>
Create my own file/image format
<http://www.sitepoint.com/forums/showthread.php?threadid=567273>
WordPress 2.6.1 has been released
<http://www.sitepoint.com/forums/showthread.php?threadid=565969>
pretty URLS
<http://www.sitepoint.com/forums/showthread.php?threadid=564034>
MORE TECHY BLOG ENTRIES - - - - - - - - - - - - - - - - - - - - -
News & Trends Blog: INDUSTRY NEWS FOR WEB PROFESSIONALS
Is It Time to Ditch IE6? (77 comments)
http://www.sitepoint.com/blogs/2008/08/25/is-it-time-to-ditch-ie6/
ColdFusion Blog: INFUSED
10 Questions for Isaac Dealey on the OnTap Framework
http://www.sitepoint.com/blogs/2008/08/25/isaac-dealey-on-the-ontap-framework/
The Week In ColdFusion: 13-19 Aug: And amongst the Gurus, an
ArgumentCollection did break out (1 comment)
http://www.sitepoint.com/blogs/2008/08/22/the-week-in-coldfusion-13-19-aug-and-amongst-the-gurus-an-argumentcollection-did-break-out/
Selling Web Design Services Blog: DOWN TO BUSINESS
SitePoint Services: Introducing Clients To Vendors (2 comments)
http://www.sitepoint.com/blogs/2008/08/21/sitepoint-services-introducing-clients-to-vendors/
Web Tech Blog: TECHNICALLY SPEAKING
Free Book Giveaway: Adobe AIR For JavaScript Developers (5
comments)
http://www.sitepoint.com/blogs/2008/08/21/free-book-giveaway-adobe-air-for-javascript-developers/
ADVERTISING INFORMATION - - - - - - - - - - - - - - - - - - - - -
Find out what thousands of savvy Internet marketers already know:
email newsletter advertising works! (You're reading an email ad
now, aren't you?)
Find out how to get YOUR sponsorship ad in this newsletter and
reach 95,000+ opt-in subscribers! Check out
http://www.sitepoint.com/mediakit/ for details, or email us at
mailto:adinfo@sitepoint.com
HELP YOUR FRIENDS OUT - - - - - - - - - - - - - - - - - - - - - -
People you care about can take charge of their Website by
effectively using the information and resources available on the
Internet. Help them learn how - forward them a copy
of this week's SitePoint Tech Times.
ADDRESSES - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Send suggestions and comments to:
techtimes@sitepoint.com
To subscribe, send a blank email to:
subscribe@sitepoint.com
The Archives are located at:
http://www.sitepoint.com/newsletter/archives.php
The SitePoint Tech Times is hosted by SparkList:
http://www.sitepoint.com/newsletters/sparklist/
The SitePoint Tech Times is (c) 1998-2008 SitePoint Pty. Ltd. All
Rights Reserved. No part of this Newsletter may be reproduced in
whole or in part without written permission. All guest articles
are copyright their respective owners and are reproduced with
permission.
SitePoint Pty. Ltd.
48 Cambridge Street
Collingwood, VIC 3066
AUSTRALIA
You are currently subscribed to The SitePoint Tech Times as:
ignoble.experiment@arconati.us
To change the email address that you currently subscribe with:
http://sitepoint.com/newsletter/manage.php
To switch to the HTML version of this newsletter:
<http://sitepoint.com/newsletter/htmlplease.php?email=ignoble.experiment@arconati.us>
To leave this list, send a blank email to:
leave-2436445-2266608.e57363ef99c8b59c8667cca2fd106cbe@sitepoint.sparklist.com
Do Not Reply to this email to unsubscribe.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
No comments:
Post a Comment
Keep a civil tongue.