Activate your free membership today | Log-in

Friday, October 10th, 2008

Reinhardt: a Client-side Dispatch Framework

Category: Dojo

Kevin Dangoor of SitePen has introduced Reinhardt a dispatch engine on the client side:

A typical server-side web framework today includes three main components: a URL dispatching to some controller object scheme, a template engine, and a data mapping facility. Currently in Dojo, you’ll find that the latter two items already exist. dojox.dtl provides the first one, and dojo.data provides the second.

Given that Dojo already offers an implementation of the Django template engine, and that regular expression-based URL dispatch was a good fit for our problem at hand, I decided to base our URL dispatch on the model provided by Django.

You can see an example using the framework which uses these patterns:

JAVASCRIPT:
  1.  
  2. var patterns = reinhardt.urldispatch.patterns("demo.code",
  3.   [/^list\/(\d*)$/, "showMovieList", ["year"]],
  4.   [/^search$/, "search"],
  5.   [/^movie\/(\d+)\/$/, "whatyear", ['id']],
  6.   [/^movie\/([\w ]+)\/$/, "whatyear", ["name"]],
  7.   [/^luke$/, "whatyear", [], {name: "Cool Hand Luke"}]
  8. );
  9.  

To get this all going you do something like this:

JAVASCRIPT:
  1.  
  2. dojo.addOnLoad(
  3.   function() {
  4.     if (!patterns.dispatch()) {
  5.       renderContent("../../default.dtl",
  6.                     {movieCount: demo.database.movies.length});
  7.     }
  8.   }
  9. );
  10.  
  11. function renderContent(templatename, variables) {
  12.   var template = new dojox.dtl.Template(new dojo.moduleUrl("demo",
  13.                                       templatename));
  14.   var context = new dojox.dtl.Context(variables);
  15.   dojo.byId("content").innerHTML = template.render(context);
  16.   pagecount++;
  17.   dojo.byId("pagecount").innerHTML = pagecount;
  18. }
  19.  

Read the full article for details, and download the entire sample, for perusal.

Posted by Dion Almaer at 6:32 am
1 Comment

+++--
3.9 rating from 17 votes

IE8 and Standards

Category: Browsers, IE

Anne van Kesteren of Opera Software has updated his post on IE 8 to cover beta 2:

  • XDomainRequest: Microsoft unfortunately continues with XDomainRequest rather than making changes to XMLHttpRequest as other browsers are doing and as is being standardized by the W3C Web Apps Working Group. (Disclaimer: I am the editor of XMLHttpRequest Level 2.)

    Some agreement was made to at least support the same protocol on the server, namely using the Access-Control-Allow-Origin header as per Access Control for Cross-Site Requests. (Disclaimer: I am the editor of that draft too.) However, IE8 only supports * as value for that header, not an origin, e.g. http://annevankesteren.nl (test). Sunava pointed out that was because the W3C WebApps WG was still debating the matter. Here is hoping they will fix the bug as there is agreement on that syntax.

  • HTML5 DOM Storage: localStorage and sessionStorage are now supported. Enumerating through them does not give the results I was expecting (I got "length" and "remainingSpace" back as well, besides the keys) and they still have a remainingSpace member that is not part of HTML5. Given that anything that gives some indication of space is highly vendor specific as it depends on encoding, compression, and type of device, they should really rename it to msRemainingSpace or some such or simply drop it.

    IE8 also supports an event named storagecommit that is not part of HTML5 which tells you when the data has been written to an XML backend format IE8 uses. The event object for used for the storage does not expose key, oldValue, and newValue. The url member is named uri and the source member is null rather than a reference to the Window object. Ouch!

  • ARIA: Aaron Leventhal recently blogged about how ARIA in IE8 is a pain. (Aaron works for IBM making Firefox and Web applications accessible and is a member of the W3C PF WG which standardizes ARIA.) In short, when IE8 renders in super standards mode ARIA will work as everywhere else, otherwise you have to use Microsoft proprietary syntax. So not only do you need to upgrade your application code to be keyboard accessible and ARIA-enabled, you will also need to upgrade it from quirks to standards mode. Alternatively, you could take the easy way out and lock out other browsers. Not nice.

He did admit that he has "only played around with Internet Explorer 8 for an hour so" :)

Posted by Dion Almaer at 5:26 am
7 Comments

+----
1.9 rating from 22 votes

Thursday, October 9th, 2008

An Interesting Twist on a Pastebin

Category: JavaScript, jQuery

Pastebins have become an important part of sharing code with colleagues. Sites such as Pastebin & Pastie.org are extremely popular because they're easy to use and very effective in letting people compare notes on source code, especially in a support setting.

Remy Sharp wanted to take the pastebin concept a step further, past the static posting of code. His idea, which he tossed around for 6 months, finally came to fruition in the form of JS Bin, a new pastebin site with a twist:

JS Bin is a form of paste bin, but with a twist. It allows you to also include the HTML and CSS to provide context to your pasty. As such, it means you can actually run the JavaScript and pass this on to a colleague to help to debug.

This is a great idea as it lets you troubleshoot your code while seeing immediate results. The feature list is well thought out as well.

  • Save private snippet
  • Remote Ajax debugging
  • Snippet URLs run entirely on their own (i.e. without the JS Bin framework around them)
  • Support to quickly inject major JS libraries including jQuery, jQuery UI, Prototype, Scriptaculous, Dojo, MooTools & YUI
  • Saves state within the open window (i.e. refresh and the code doesn't reset)

The ability to inject many of the popular JavaScript libraries is especially important and I would highly recommend individual project teams to contact Remy directly to have their libs included.

To give this a run, I'd suggest going to the JS Bin site and putting it through its paces. In addition, Remy has produced two videos which go into detail on how to leverage JS Bin:

Posted by Rey Bango at 10:52 am
5 Comments

+++--
3.9 rating from 14 votes

Chofter: search mashup using all things Dojo

Category: Dojo, Showcase

Shane O'Sullivan has built a nice search mashup experience called Chofter. It uses all things Dojo, including:

  • Layouts, Dialogs, Menus and ContentPanes for the user interface.
  • dojo.data and dojo.rpc for data transfer.
  • dojox.dtl (Django Templating Library) for transforming search data into visuals.
  • dojo.fx and FisheyeLite for eye candy

Posted by Dion Almaer at 10:50 am
1 Comment

+++--
3.2 rating from 13 votes

How does the scoping work with eval()?

Category: JavaScript

Rakesh Pai wanted to understand scope issues with eval and found a few surprises.

He started with the snippet:

JAVASCRIPT:
  1.  
  2. var foo = 123;
  3. var bar = {
  4.     changeFoo: function() {
  5.         // We'll keep changing the following snippet
  6.         alert(this);
  7.         eval("var foo = 456");
  8.         // Changing snippet ends
  9.     }
  10. };
  11.  
  12. bar.changeFoo();
  13. alert(foo);
  14.  

And then he rev'd it in different ways and captured the output.

His conclusion?

What I think of these results:

  • I don't know what Firefox is doing in case 2, and for some reason Safari Nightlies seem to be following it. Maybe it's just beyond my understanding, but case 2 is not supposed to be different from case 1. Why does case 2 operate in global scope? If window.eval is different from eval, case 3 shouldn't all have given errors. Someone please help me understand that $hit.
  • Case 4 makes sense, but that's a non-standard behavior in Firefox. Understandable that no one else exhibits it.
  • IE baffles me in case 5, and Chrome seems to ape it. In this scenario, the anonymous function is supposed to have the global scope - so, in this case, this should point to the window. WTF is happening here!
  • Consistent with case 2 above, Firefox and Safari Nightlies continue to display weird behavior in case 6. For some reason, in these two cases, the eval operates in the global scope.
  • Now, I have no idea why, but only cases 8 and 9 seem to really work at all. This is despite Doug Crockford going on and on about not using with constructs. It's also despite being beyond (my) understanding about why the with should make any difference to the eval, since eval is part of the window object.

All in call, if you are going to be evaling JavaScript (not JSON), and you want the eval'd code to run in the global scope, you should use the with block around the JavaScript snippet. Or else, you can lose a lot of hair handling cross-browser issues.

Posted by Dion Almaer at 10:32 am
2 Comments

+++--
3 rating from 11 votes

Exclusive iPhone in Action Chapter Downloads

Category: iPhone

Now that the NDA has been released, book publishers are finally able to get out their wares. Christopher Allen and Shannon Appelcline have written iPhone in Action, and have kindly given the Ajaxian community free downloads of a couple of the early access chapters:

I hope to see books that focus on what you can do with the Web APIs too of course ;)


This article is based on iPhone in Action, to be published January 2009. It is being reproduced here by permission from Manning Publications. Manning early access books and ebooks are sold exclusively through Manning. Visit the book's page for more information.

Posted by Dion Almaer at 10:26 am
Comment here

++---
2 rating from 3 votes

Wednesday, October 8th, 2008

Antisocial: 3D in Canvas with Sound

Category: Canvas, Showcase, jQuery

Gasman has created Antisocial, a very enjoyable demo of Canvas doing fake 3d and 2d along with that ZX Spectrum sound that you loved as a kid.

Check out the tool to see where the magic happens, and make some music, Spectrum style!

I feel like we have been light on showcases recently, so please email us if you have seen a cool use of Ajax that we haven't picked up on!

Posted by Dion Almaer at 5:42 pm
9 Comments

+++--
3.8 rating from 18 votes

Pimp My Site with CSS and Prototype

Do you like some code pimpage? We saw a couple of interesting posts on this recently in fact.

First, our own Christian Heilmann took a table based layout, and in short order turned it over to the light via YUI Grids and CSS.

He took this:

And it quickly became this:

He has made the code available, and is asking if people want more information. I would love to see more of this content myself... people that know their stuff explaining the how and the why.

This leads us from CSS to JavaScript. The Prototype team put out a call for pimping. Send them some code, and they will show you how they would write it, inevitably in that Prototype "kinda like Ruby JavaScript" style. I look forward to the first showing!

Posted by Dion Almaer at 12:19 pm
3 Comments

+++--
3.7 rating from 20 votes

The myths and reality of XHTML

Category: W3C

Lack of support for XHTML is a fact of life on the web in 2008. Prior to the 3.0 series of Firefox the XHTML processor in Gecko was so poor that Mozilla’s own engineers recommended against it[27]; no version of Internet Explorer up to, and including, IE 8 support XHTML at all, and a number of other browsers such as Lynx were never written to handle XML in the first place.

The above quote comes from XHTML?—?myths and reality by Tina Holmboe, a member of the XHTML Working Group.

It is a nice piece that delves into:

  1. Introduction
  2. The Purpose of XHTML
  3. XHTML and the Content Type
  4. Strictly XHTML
  5. Lack of support
  6. Content–Negotiation
  7. Recommendations

Posted by Dion Almaer at 6:07 am
14 Comments

+++--
3.1 rating from 18 votes

Aptana Jaxer 1.0 RC

Category: Aptana

The Jaxer team has released a release candidate for Jaxer 1.0.

Here a synopsis of all the new features and improvements that have gone into this latest release candidate:

  • Jaxer.Sandbox: HTTP-level control; support readyState, toHTML, waitForCompletion
  • Built-in, extensible dispatching for RESTful and RPC service requests
  • Fast, native JSON support
  • Improved APIs for HTTP Request and Response
  • More flexible handling of application configuration
  • Many bug fixes, smaller improvements, and cleanups

They are moving pretty fast, so are looking for feedback before they wrap up a final 1.0 release.

Posted by Dion Almaer at 5:12 am
3 Comments

++++-
4.2 rating from 26 votes

Extreme JavaScript Performance; John Resig on Ars

Category: JavaScript, Performance

Ars Technica has a new columnist, John Resig. His first piece is on Extreme JavaScript Performance which has started to come to us in abundance recently!

His article focuses on the latest updates to the fish, SquirrelFish Extreme:

A popular technique that is gaining traction amongst JavaScript engine implementers is that of optimizing the engine, while it's still processing the JavaScript code, to determine the "type" of the object that is being used. Since JavaScript doesn't include any sort of explicit type system JavaScript engines are frequently forced to check and re-check the values that they are handling, to insure their integrity. SFX rounds out the collection of other modern JavaScript engines, namely V8 and TraceMonkey, to provide this form of polymorphic inline caching. Interestingly, the idea for this form of caching comes from the Self programming language, the origin of many of the ideas in JavaScript (such as using prototypal inheritance instead of the more-common classical form of object inheritance seen in languages like Java).

JavaScript engines are serving as the test bed for new forms of dynamic language optimization. No other language is seeing this level of competition and rapid improvement that JavaScript is. This is optimal considering that JavaScript is one of the most widely-deployed programming languages available.

The SquirrelFish Extreme release currently stands as the fastest JavaScript engine [based on SunSpider] (although that's certain to change as healthy competition continues).

Posted by Dion Almaer at 4:17 am
4 Comments

+++--
3.8 rating from 23 votes

Tuesday, October 7th, 2008

navigator.geolocation now available in Firefox via Geode

Category: Mozilla

When I posted about using navigator.geolocation now the only support that I had was via Gears and the ClientLocation API. I wrote the shim to try to get you the W3C API no matter what, and today we have the first implementation in a browser, via Geode.

Geode is the latest project in Mozilla Labs that gives you that API in Firefox. Aza Raskin has a nice Food Finder application that ties it together with local search and maps.

Differences between Geode and Geolocation in Firefox 3.1

Geode and the Geolocation Services in Firefox 3.1 will use the same W3C API for Geolocation, meaning that the same Javascript code will work in both. The still-in-developement Firefox 3.1 version will allow the user to choose a geolocation service provider, which can either be a peripheral device like a GPS, or a web-based service provider like we’ve used in Geode. We’ll be using the feedback we get from Geode, as well as the feedback we see on the upcoming Firefox 3.1 Beta and Fennec Alpha releases, to refine the feature before shipping it in a future Mozilla product release. We’re particularly interested in ensuring that the final implementation is as sensitive to user privacy and choice as possible.

They also got some partners to start playing with this:

To kick off Geode, two other websites have started innovating with location. Both require accounts before you can try them out.

Pownce is a service that makes it easy to send stuff (music, photos, events, and messages) to your friends. Adding the power of location — where you are when you uploaded a photo or sent a message — paints a compelling picture that helps you discover friends and activities around you. Head there to see it in action (you’ll have to sign up for an account).

Yahoo! Fire Eagle is a service that acts as a broker for your location, creating a single place where any web service, from any device can get access to your last updated location. Fire Eagle integrates with Geode so that you’ll never have to manually enter your location again. Once you have a Fire Eagle account, you can see Geode working here.

Posted by Dion Almaer at 1:32 pm
2 Comments

++++-
4.5 rating from 12 votes

Pyjamas: GWT for Python

Category: GWT, Python

Last week, we posted a story about deploying GWT to PHP back-ends. We've got another GWT-ish post this week: Pyjamas, a sort of GWT for Python.

The SourceForge project page has a brief overview and pointers to a tutorial, a widget showcase, and more.

Posted by Ben Galbraith at 8:00 am
2 Comments

+++--
3.7 rating from 15 votes

IE 8 beta 2 Ajax features

Category: Browsers, IE

Sunava Dutta has detailed the enhancements made to IE 8 beta 2 for Ajax developers including XDR, XDM/postMessage, DOM Storage, offline detection, and more. A lot of great stuff!

XDomainRequest (XDR)

This is an object built from the ground up to make client-side cross-domain calls secure and easy. To reduce the chances of inadvertent cross domain access, this object requires an explicit acknowledgement for allowing cross domain calls from the client script and the server. Additionally, it reduces the need for sites having to resort to the dangerous practice of merge scripting from third parties directly into the mashup page. This practice is dangerous because it provides third parties full access to the DOM. All this comes with the added benefit of improved client-side performance and lower server maintenance costs thanks to the absence of a need for server farms for proxying.

During the Beta 1 timeframe there were many security based concerns raised for cross domain access of third party data using cross site XMLHttpRequest and the Access Control framework. Since Beta 1, we had the chance to work with other browsers and attendees at a W3C face-to-face meeting to improve the server-side experience and security of the W3C’s Access Control framework. As a result, we’ve updated XDR to be explicitly compliant with syntax and directives in the sections of Access Control for requesting simple public third-party data anonymously on the client! (Section 5.1.3 in the Access Control Process Model)

The updates to XDR from Beta 1 allow IE8 to request data from the domain's server by sending an Origin header with the serialized value of the origin of the requestor. IE8 Beta 2 will only return the response if the server responds with Access-Control-Allow-Origin: *, instead of allowing the XDomainRequestAllowed: 1 header as we did in Beta 1. Other changes include support for relative paths in the open method, and restricting access to only HTTP and HTTPS destinations.

Cross-document Messaging (XDM)

Cross-document messaging is another powerful cross-domain feature that I’ve blogged about in the past. Rather than make a backend request to a remote Web service, this allows sites hosting third-party IFrame-based "gadgets" or components to communicate directly with the parent, without unsafely violating the same site origin policy. This has advantages including improved performance and reliability, as developers don’t have to resort to workarounds that behave differently between browsers and have unwanted side-effects. This technique also removes the need for embedding third-party script in your page, lessening the chance of potential information disclosure vulnerabilities like the disclosure of your sensitive data (such as information in your social network profile) to third parties without your consent.

Beta 2 updates here include moving the onmessage handler from the document object to the window object to better align with the updated HTML 5.0 draft.

window.attachEvent("onmessage", HandleMessage);

We also replaced e.URI with e.origin, which is serialized form of “scheme” + “host” + “non-default port”. This is far safer as the URI can carry potentially sensitive information from the origin site that is not needed by the recipient for the decision to grant or not grant access.

if (e.origin == 'http://www.contoso.com') 
       
               // process message text     
        }

Finally, the HTML 5.0 draft also mandates that the targetOrigin parameter for the postMessage method now be made a required parameter, as opposed to an optional one. This will make it difficult for developers to make errors by requiring an explicit acknowledgement of the target destination of the message by specifying the origin <URL> or wildcard <*>.

 frameOther.postMessage("This is a message", "http://example.com");

DOM Storage

Today, web pages use the document.cookie property to store data on the local machine. Cookies are limited in capability by the fact that sites can only store 50 key/value pairs per domain. Furthermore, the cookie programming model is cumbersome and requires parsing the entire cookie string for data. While cookies are useful for marking transitions and changes on the client to the server as they are sent with the request headers in chunks of up to 4KB, IE8 brings better alternatives for scenarios involving persisting data on the client and distinctly maintaining sessions in different tabs. The W3C’s HTML 5 DOM Storage objects provide a much simpler global and session storage model for key/value pair string data. Sites can store data for the life of a tab or until the site or user clears the data.

Updates for Beta 2 include changing the name of the persistent globalStorage attribute to localStorage and the removal of the need to specify the domain when writing to the localStorage

// Store a key-value pair.
localStorage.setItem("FirstName","Sunava");

Finally, we also included improved support of the updated onstorage HTML 5.0 event returned when the storage is changed. We now return the URI when the local storage is changed, so that handlers for pages can know who carried out the latest transaction in the storage space in addition to providing the source to the window of the origin. Furthering the good news, the HTML 5.0 Working Group has incorporated the clear method, which we shipped in Beta 1, into the draft. This essentially allows for script to clear all items accessible in its storage space without having to iterate though the keys.

Connectivity Event

The navigator.onLine property and online/offline events now work on Windows XP as well as Windows Vista. The work to enable this was not trivial, as connection awareness in Windows XP is not quite as advanced as Windows Vista. That said, this will be extremely beneficial for developers, who we believe shouldn’t have to worry about OS differences. The value of connectivity events is particularly appealing when used in conjunction with the localstorage, where data can be cached in case of network loss!

XMLHttpRequest

Introducing the XDomainRequest object in IE8 hasn’t diverted our attentions from constantly tweaking and improving XMLHttpRequest, which will continue to be our flagship object for same-domain communications. Post-Beta 1 energies here have focused on a few bug fixes around reliability and working with the Web Apps Working Group to clarify and improve the draft specification, our compliance with it, and W3C public test cases. A timeout method introduced here in Beta 1 for the convenience of developers is currently being evaluated for adoption in the XMLHttpRequest spec.

// Sets timeout after open to two seconds.
xhr.timeout             = 2000;

ToStaticHTML, to JSON, and fromJSON

What do you do with the strings returned from third parties using XDomainRequest or Cross-document Messaging? In today’s world of increasing script injection and Cross-site Scripting (XSS) attacks, having the option of passing these through a safe parser comes as a welcome relief. As detailed in Eric Lawrence's post on Comprehensive Protection for IE8 Security, toStaticHTML provides a powerful way of sanitizing your strings by purging potentially executable content.

//Calling:
window.toStaticHTML("This is some <b>HTML</b> with embedded script following... <script>alert('bang!');</script>!");

//will return:
This is some <b>HTML</b> with embedded script following... !

In addition, IE8 Beta 2’s toJSON and fromJSON methods provide improved performance as opposed to non-native Javascript deserializers and serializers. Our implementation is based on the ECMAScript 3.1 proposal for native JSON-handling which uses Douglas Crockford’s json2.js API. In addition to the performance benefits of going native, the JSON parser provides a safe alternative to the eval() method, which has been a common and dangerous way to revive JSON objects, and could allow arbitrary script functions to execute.

Posted by Dion Almaer at 7:53 am
5 Comments

+++--
3.2 rating from 49 votes

Regex performance in modern JSVMs

Category: JavaScript, Performance

Based on its performance on the regexes it does handle, WREC (WebKit Regular Expression Compiler) is indeed an awesome design. regexp-dna.js, however, is flawed and exaggerates SFX performance.

We could use nanojit to make a regex compiler for SpiderMonkey that would perform as well as WREC. But I don’t know if it’s worthwhile yet. Regex performance is much less important for today’s web than it is for SunSpider–I hope to link to a report on that in a future post.

That was the conclusion that David Mandelin of the Tamarin project as he looked into how "SquirrelFish Extreme (SFX) is kicking our butts so badly on regexp-dna.js."

I love David's posts, as they go into the real meat of the tech:

Technical details: the design of WREC. There are two main ways to implement regular expressions: using a backtracking matching engine, or by transforming the regex to a finite automaton (NFA, aka “state machine”), which does not backtrack. Most Perl-type regex engines, including both SpiderMonkey’s and WREC, follow the backtracking design. I don’t know the exact history of that choice, but at present it is much easier to implement features like group capture and backreferences in the backtracking design. Also, although some regexes scale only if implemented as NFAs, my tests suggest that many simple regexes, including those in SunSpider, are faster with backtracking.

As of this writing, WREC’s implementation strategy is dirt simple (which is a good thing). There are no transformations or fancy optimizations on the regex. WREC simply generates native code that directly implements the backtracking search. Thus, within a single match operation, there are no function calls, no traversals of regular expression ASTs, and few option tests, so almost all of the overhead is eliminated.

WREC’s code is very easy to read, so if you want to know exactly how it works, just read it in WREC.cpp. It’s also great example code for anyone implementing a compiler for a simple language like regular expressions. The basic plan is to parse the regular expression with functions named things like parseDisjunction (the | operator). Those functions directly call functions like generateDisjunction that generate the native code using the same assembler that the call-threading interpreter uses. There’s also the oddly named “gererateParenthesesResetTrampoline”. Inexplicably preserved typo, or watermark to detect copying of WREC code?

Posted by Dion Almaer at 5:57 am
Comment here