As preparation for an upcoming tech talk about Placemaker I thought it would be good to take a bit of the pain out of the geolocation service by making an interface for it. Placemaker works the following way: you post some content or a URL to it, it goes through the content or gets the content from the URL and analyzes it. It then finds geographical locations in the text and disambiguates them (for example to skip names like "Jack London" and not consider it the city London). Finally you get it back as XML.
The annoying thing is that Placemaker only support POST request and does not have a JSON output - for now. GeoMaker allows non-developers to enter some text or a URL, filter the results (using YUI datatable) to remove false positives (no system is perfect) and get the embed code for a Yahoo Map or a list of microformatted locations as copy+paste. See the screencast to get the end user experience:
Of course, every time you build something like that, red-blooded developers will ask for an API to do the same thing (and pointing them to Placemaker wasn't enough). So here it is:
http://icant.co.uk/geomaker/api.php takes two parameters: url of the web document to load and output which could be map, kml, microformats, csv, or json (with callback for JSON-P). Using this you can analyze a url in JavaScript and get the data back as an array:
Kyle Simpson has developed LABjs, a library that lets you define your JavaScript file dependencies, and then loads them as efficiently as possible.
Kyle told us:
This project is a simple little tool (1.6k compressed!) for being able to load javascript files dynamically. It's like a lot of similar projects where the goal is to improve the speed of page load by allowing scripts to load in parallel. The thing it does slightly differently than most others like it is it allows you to "block", which is to say, load one or more scripts in parallel, then wait for them to finish, before going on to something else, like loading more scripts.
What I wanted was a pattern where I could load scripts in parallel, just like with script tags, but also block and wait if there was an explicit ordering dependency that required it.
What most loaders fail to do well is let you define "dependencies" simply based on loading order. With regular script tags, the browser blocks for you, so you can make sure for instance that jquery.js loads before jqueryui.js. But imagine you've got 3 scripts that can download in parallel (not dependent on each other), and then two more that need to wait for those 3 to load. You can't do that with script tags, and you also can't do that very easily with a lot of the script loaders/frameworks that I've found.
Most of them rely on intrusive concepts to do "dependency" management. For instance, each child script has to "signal" (callback) that it's done loading, to the parent page. Or the parent script and child scripts have to explicitly declare dependencies using some framework or conventions. Also, some other loader libraries rely on attaching a single load callback handler for EACH script. This makes it awkward or difficult to wait for several to load at a time, before proceeding, since you as the author have to keep track of what has loaded yourself.
jsLAB lets you load pretty much any script file, whether you control it or not, with no intrusion or convention for dependencies, other than the order and blocking that you define. It keeps track of what you've asked for and what has downloaded, only loads a unique script filename once, and lets you only define your handler once for a set of scripts that will load together in parallel. The API style (with chaining) makes is very easy to convert a set of script tags in your page into code to load them, without having to worry that race conditions will cause issues for scripts loading in the wrong order if there are implicit dependencies involved.
In the above example, "jquery.ui.js" and "myplugin.jquery.js" can load in parallel because there's no dependencies, but they will wait for "jquery.js" to load first, since they depend on it, and then "initpage.js" will wait for all of them to load before it runs, to it makes sure all code it will call is in place, similar to a $document.ready(...) concept.
The page link above also shows a few other variations on the .script(...) signature. For instance, you don't have to do a single script() call for each file (though I think it makes thing more readable). You can pass as many scripts singularly as parameters to one script() call. You can also pass an array of scripts, and it will loop through them and load them in the same way. Lastly, you can pass in an object instead of string, and the object literal can contain "src", "type", and "language" specifications, if you want to override the defaults of "text/javascript" and "Javascript", for some reason.
We’ve spent a lot of time in this release cycle refining the core elements of YUI 3 — YUI, Node, and Event — to ensure that we have the right API going forward. Performance is improved, and we’ve refined our module/submodule structure. In some cases we’ve added significant new features, including intrinsic support for event delegation in the Event package; however, the focus is on moving the base library to production quality.
Several YUI 2.x components make their YUI 3 debut in this release:
DataSource: YUI’s data abstraction layer provides a standard interface into data sets, regardless of the data’s origin (local, XHR, XSS, etc.) and format (JSON, XML, CSV, etc.);
ImageLoader: ImageLoader allows you to defer the loading of images that aren’t in the viewport when the page paints, throttling bandwidth usage and improving performance;
History: The History component gives you control of the brower’s back button within the context of a single-page web application;
StyleSheet: StyleSheet makes it easy to create and modify CSS rules on the fly, allowing you to dynamically style page elements with fewer repaints.
As part of the more granular packaging in the new codeline, we’ve created separate YUI 3 modules to house functionality that in YUI 2 was bundled with other components. Cache, DataType and DataSchema debut in this release; each of these used to be a part of DataSource.
To keep up to date, check out the roadmap and dashboard that the team keeps up to date.
We have been sandboxing JavaScript in iframes for a long time. The Web Worker API has the nice property that it doesn't have access to objects like document and the like, and just runs code that you can pass over to it.
With this, Elijah Grey has created an experimental jsandbox API that gives you an eval function that you pass in some code, and optionally input data, callback for results, and an onerror callback.
The religion behind a simple $ has been fierce in the Web world. MooTools has decided to make the Dollar Safe Mode which is similar to cousins such as jQuery.noConflict (in MooTools case it just looks for the $ function). Now you can just use document.id if you want to play in the wild, or wrap up in a closure to be nice:
Please note that MooTools will probably remain incompatible with other frameworks that modify native prototypes, as there will probably be more name clashes. This isn’t a cross-framework compatible MooTools version by any means, nor does it want to be. The whole point is not to “steal” the dollar function from other libraries.
In other MooTools news, MooTools Core Dev Thomas Aylott (subtleGradient) shows another example of overriding document.write():
I created a replacement for document.write that saves the arguments and then injects them into the page after the dom is ready. This is useful for embedding gists on your page since you can use the additional filter option to reject stuff from being written to your page. This would also be really handy for sites that include JavaFX or certain ads or anything that requires the use of document.write on your page. By deferring the injection of that stuff until after the dom is ready your visitors see the page content before any of the extras like Java applets or ads begin to load.
whatToShow, // a set of constants to filter against
filter, // an object with a function for advanced filtering
entityReferenceExpansion // if entity reference children so be expanded
);
This is excessive for what should be, at most, a simple way to traverse DOM nodes.
One part of the critique involves the common pattern of bitwise operators that are common in C, C++, and a bit of Java (and elsewhere too). When space is at a premium, these are a good choice. There are also some nice side effects when you use them (building up the flags, munging them later, etc).
However, as John points out, these are more for CSci students than for the average Web developer.
But then the crazy comes in: In order to select multiple, different, types of nodes you must OR together the properties to creating a resulting number that'll be passed in.
For example if you wanted to find all elements, comments, and text nodes you would do:
I'm not sure if you can get a much more counter-intuitive JavaScript API than that (you can certainly expect little, to no, common developer adoption, that's for sure).
He goes on to propose some more Webby APIs such as:
By default we should always favour asynchronous XHR to help the responsiveness of our Web applications. However, have you ever wanted a way to serialize your XHR calls because you needed to do things in sequence as B relied on what came back from A?
You could call a synchronous Ajax call, but that locks up the browser. Thibaud Lopez Schneider has written up his thoughts here showing the difference between synchronous Ajax:
and async calls with magic to serialize them:
He then went and created a simple example code generator at asynchronous.me. It is interesting to look at the code of the serialized version, and see that it doesn't do anything complex.... just passes in the next function to run as a callback:
It includes compatibility tables, and will try to run the tests on your browser to give you feedback. It also includes sample code to check web browser support that you can use in your own projects.
Surprisingly, a topic of named function expressions doesn’t seem to be covered well enough on the web. This is probably why there are so many misconceptions floating around. In this article, I’ll try to summarize both - theoretical and practical aspects of these wonderful Javascript constructs; the good, bad and ugly parts of them.
In a nutshell, named function expressions are useful for one thing only - descriptive function names in debuggers and profilers. Well, there is also a possibility of using function names for recursion, but you will soon see that this is often impractical nowadays. If you don’t care about debugging experience, you have nothing to worry about. Otherwise, read on to see some of the cross-browser glitches you would have to deal with and tips on how work around them.
He then goes into a ton of examples of weirdness in different browsers, and fun code like this:
When you provide a JSON output for developers it does make sense to also allow for a callback parameter. That way your code can be used in script nodes without having to use any backend at all. Commonly this is called JSON-P and has been covered here in the long long ago. One of the issues with JSON-P is that when the callback method is not defined it throws an error.
The Bing API is the first instance where I have seen that they worked around that as the output is this:
I have no clue what the /* pageview_candidate */ is about and frown upon omitting the {} of the if statement, but I must say I do like this. One issue is that while end users don't get annoyed with errors, developers don't have a clue what happened either as the error is silent. One proposal would be to use a console.log() when there is an error:
James Coglan has updated JS.Class, his implementation of Ruby's object system in JavaScript.
This release includes a Hash implementation, HashSet, an updated Ruby 1.9 Enumerable module with enumerators and Symbol#to_proc functionality, and an improved package loader that supports parallel downloads and runs on SpiderMonkey, Rhino and V8.
The package manager has been improved with a new API, parallel downloading of files, and support for server-side environments such as SpiderMonkey, Rhino and V8. It also supports user-defined loader functions for transparent integration with Google and Yahoo!’s packaging systems.
The Enumerable module has been updated with plenty of methods from Ruby 1.9, and now supports enumerators, and Symbol#to_proc-like functionality whereby a string, MethodChain or any object that implements toFunction() can be used as an iterator.
The core object methods now live in Kernel, and we’ve added new methods: tap(), equals(), hash() and enumFor().
The double inclusion problem is now fixed; no current Ruby implementation seems to support this properly.
Ancestor and method lookups are now cached so callSuper runs about twice as fast.
The JavaScript InfoVis Toolkit provides tools for creating Interactive Data Visualizations for the Web. The code has been updated:
The library has been split into modules for code reuse.
All visualizations are packaged in the same file. You can create multiple instances of any visualization. Moreover, you can combine and compose visualizations. If you want to know more take a look at the AdvancedDemos.
This Toolkit is library agnostic. This means that you can combine this toolkit with your favorite DOM/Events/Ajax framework such as Prototype, MooTools, ExtJS, YUI, JQuery, etc.
You can extend this library in many ways by adding or overriding class methods. The JavaScript InfoVis Toolkit has a robust (and private) class system, heavily inspired by MooTools’, that allows you to implement new methods in the same class without having to define any new Class extension. By creating mutable classes you can add new custom Node and Edge rendering functions pretty easily.
Custom visualizations are created by adding or changing Node/Edge colors, shapes, rendering functions, etc. You can also implement many controller methods that are triggered at different stages of the animation, like onBefore/AfterPlotLine, onBefore/AfterCompute, onBefore/AfterPlotNode, request, etc.
You can also add new Animation transitions like Elastic or Back with easeIn/Out transitions.
If you want to know more about these features please take a look at the Demos code.
A complete API documentation generated with Natural Docs, with some Narrative Documentation and Syntax Highlighted Code Examples.
Tero Piirainen has created a new package of jQuery Tools.
This library contains six of the most useful JavaScript tools available for today's website. The beauty of this library is that all of these tools can be used together, extended, configured and styled. In the end, you can have hundreds of different widgets and new personal ways of using the library.
This library is open source and dual licensed under MIT and GPL 2+ licenses.
Sergey Ilinsky, formerly of Ajax pioneer Backbase, has created a new Ajax toolkit called Ample SDK. The best way to describe Ample SDK is that it's a browser-within-a-browser, but not in the visual sense. Rather, it aims to implement in JavaScript the stack of rendering technologies typically delegated to the browser. For example, Ample currently lets you use Mozilla's XUL to create cross-browser applications.
Here's an example of how you could use Ample SDK to render a XUL interface in the browser:
<body>
<!-- other HTML code -->
<script type="text/javascript">ample.open()</script>
<xul:menulist xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<xul:menupopup id="items-popup">
<xul:menuitem label="Item 0" value="0"/>
<xul:menuitem label="Item 1" value="1"/>
<xul:menuitem label="Item 2" value="2"/>
</xul:menupopup>
</xul:menulist>
<script type="text/javascript">ample.close()</script>
<!-- other HTML code -->
</body>
(Sorry for the old-school, ugly <pre> above--our code formatter chokes on XML namespaces, used in the XUL elements above.)
The Ample SDK compatibility table, shown above, gives you a sense of the scope of the project: to implement technologies like XUL, SVG, HTML 5, XHTML, and so forth, all in JavaScript--and render them across modern and legacy browsers like IE 5.5.
When Brendan Eich first hinted several years ago that the browsers would get fast, it spurred a lot of folks to wondering whether the future of feature innovation would be primarily in the JavaScript library space, and the browsers would focus on being JavaScript run-times and graphics abstract layers.
Ample SDK raises the question anew. Should we push the rendering layer to JavaScript libraries? What do you think?
Zohaib Sibt-e-Hassan has created a Mootools based mouse gesture library Moousture that is based on simplicity:
A probe, which probes the pointing device. Currently there
is a Moousture.MouseProbe (P.S. I am planning to test it on iPhone and
build any seprate probe for that).
A monitor, which tests the stability of probed
device on given intervals and accordingly notifies Moousture events
(onStable, onUnstable, onMove).
A Moousture recorder class that records the mouse
movements and invoke the guesture object passed to it.
// Create a guesture matcher, currently there are only two gesture objects Moousture.LevenMatcher, and Moousture.ReducedLevenMatcher.
gstr = new Moousture.ReducedLevenMatcher();
// Add gesture vectors to matcher object, (see details below in Create your own gestures).
gstr.addGesture([3,2,1,0,7,6,5,4], ccwCircle);
// Guesture callback function takes one parameter error recieved from matching algorithm. Threshold that value (if required) to make your gestures more sleek.
function ccwCircle(error){
if(error>= 0.6)return;
...
}
// Create a probe object that will probe the pointing device. Currently there is a mouse probe that take the $(element) to probe for. So passing a div id will cause the probe to trigger events only when they occur on the passed DOM element.
probe = new Moousture.MouseProbe($(document));
// Create a recoder object to record the movement , maxSteps and minSteps in options object will specify the maximum and minimum number of steps to be recorded, and macher is required matcher object to trigger the appropriate gesture.
recorder = new Moousture.Recorder({maxSteps: 20, minSteps: 8, matcher: gstr});
// Create a monitor specifying the interval to poll and the amount of error allowed for gesture in pixels.
monitor = new Moousture.Monitor(30, 2);
// Finally start the monitor.
monitor.start(probe, recorder);
// You can stop the gesture triggering any time by calling .stop() of monitor object.