Articles by ‘Aaron Newton’

More Than Meets the Eye: Form.Request

Written By Aaron Newton, on Thursday, March 4th 2010, 5:06pm

MooTools More features a diverse, powerful collection of Classes (60 plugins!!) and some are my favorite tools that I use over and over again. I thought I’d take some time to dig into some of the plugins in MooTools More that I think are interesting and really useful that maybe you haven’t had time to really sink your teeth into (or, perhaps, you haven’t found a reason to). So I’m going to take some time to talk about some of the plugins in More each month, sharing not only how they work, but how they work together and maybe even why you’d use them. Today I’m going to talk about the Form.Request plugin.

Request and Request.HTML

MooTools Core ships with three AJAX modules, two of which include element methods (Request.JSON, the third module, doesn’t alter the Element prototype). Request.js provides the Element prototype with a send method that lets you post a form (as in, $('myFormElement').send([request options go here])), and Request.HTML.js provides the Element prototype with a load method that lets you replace the contents of any DOM element with text returned from a server request (as in $('myElement').load([request options go here])). I use these fairly often, though I probably use the Request and Request.HTML constructors just as much if not more. But in my own work I found myself needing the combination of these two things; I want to submit the form and load the response into a DOM element. Turns out, I do this all the time.

Part of writing idiomatic MooTools code is encapsulating functionality into Classes. As I’ve posted before, I do this with almost all the code that I write. The only code that I author that isn’t a class (or a static object) is a DomReady statement that instantiates classes. So when I have a pattern as clear as this - submitting a form and updating the DOM with the response - it’s time to write a class.

Form.Request

Form.Request, unlike Request.HTML, is not an extension of the Request class (that’s why it’s not Request.Form). Because it is not a Request.HTML instance, it has a reference to an instance of Request in it. Form.Request’s options include a requestOptions object that gets passed along to this instance so you can configure it however you like. By default, Form.Request derives as much as it can from the form element itself. It gets its URL from the action property and the method from the method property. The user submits the form and it cancels the submit event. Form.Request inspects that event to see if the user clicked a button and, if so, sends the name/value of that button along with the data like a regular form submission. Finally, it provides an extraData option so you an send along key/values with the form in addition to those in the inputs that the user fills out.

When the form returns a response, it handles it pretty much how Request.HTML handles any other response. It injects the HTML and evaluates any scripts in the response (this is an option, too).

And what about what we set out to do? To provide a method for Element that is the combo of load and send? The plugin provides the Element prototype with a formUpdate method that works just like those two methods combined (as in $('myForm').formUpdate({ update: $('myTarget') }), which sends the form and updates $('myTarget')).

Demo Time!

Here’s a simple demo to play with. Note how our html is plain old vanilla web 1.0 form stuff. Nothing fancy. And our JavaScript is dead simple (to get the default behavior).

Getting Fancy

Hmmm. Well, our behavior here leaves a little to be desired. The main thing that seems to be missing is any indication that something is changing - that the form has been submitted and we’re waiting for a response from the server (MooShell provides a 2 second delay on the response to simulate normal web latency). We could add an event to our instance to tell the user that something is going on, like so:

Getting Fancier

Here’s where the fact that this plugin is part of MooTools More comes into play. MooTools More includes a plugin called Spinner. I’ll talk about it in depth some other time, but in a nutshell, it puts an Ajax indicator over an element that’s being updated. It integrates with Request.HTML and Form.Request configures it for us. This happens automatically (unless you disable it in the options) and all we have to do is skin it. In this example, I’ve moved our message (that we’re sending the submission) into the Spinner options.

This magic happens without much effort for us so long as we have Spinner.js in our page. This is the default behavior. We don’t even have to specify the message text if we’re content with just the spinner image.

Even More Integration

One other thing Form.Request integrates with (also in the MooTools More library, naturally) is Form.Validator. That’s another plugin I’m not going to spend a ton of time describing in today’s post - we’ll save it for a later post as it has lots of nifty things in it. But, basically, Form.Validator (and its subclasses) provide instructions for users who are filling out a form on the fly. Form.Request integrates with it so that you don’t have to do anything to make them play nice together. Both intercept the submit event and both prevent its default behavior (i.e. sending the form), except that the Form.Validator class only stops it if the form is invalid. If Form.Request didn’t respect this privilege, it would send our form even if the Form.Validator stopped the default submission event. To get them to cooperate, all you have to do is create an instance of Form.Validator on the form. Example:

In this example, we set a minLength value for our form (50 characters). The default html in the textarea is only about 45 characters, so if you just hit submit you’ll see a red error message show up. Add some more text to our example, hit submit, and the error winks out and our form sends just as before.

Appending Results

One last trick up our sleeves here; you can append results instead of overwriting the contents of our target. Think of a to-do list kind of interface, where adding a value adds a new item to a list. To get this behavior, we just substitute Form.Request.Append into our example. There are some additional options; by default it uses another MooTools More plugin, Fx.Reveal, to smoothly transition elements into view. You can also specify if the item is appended to the top or the bottom of the container. Example:

THEND

So that pretty much covers Form.Request. I hope you find it as useful as I do. If you find it useful and fun, post a link in the comments showing off what you’ve done with it. In my next post I’ll pick another plugin (or plugins) to dig into and show off their capabilities. If there’s one you’d like to learn more about, post a suggestion for my next post in the comments.

Aaron Newton is a contributor to MooTools and the principal developer of MooTools More. He is the author of the book MooTools Essentials as well as the Mootorial online MooTools tutorial. He posts (rarely these days) at his blog Clientcide.com and (much more often) on Twitter as anutron.

MooTools More 1.2.4.3, 1.2.4.4

Written By Aaron Newton, on Tuesday, February 9th 2010, 9:10pm

UPDATE: 1.2.4.4 is also released; there was a new bug in Tips introduced in 1.2.4.3 that was immediately patched.

This is mostly a bug fix release.

  • Nearly 50 bug fixes (see the milestone for 1.2.4.3 in Lighthouse).
  • Keyboard:
    • Added some support for just pressing ‘shift’, ‘control’, or ‘alt’
    • Added a bunch of keycodes for Mac compatibility
  • Keyboard.Extras:
    • Support for “shortcuts” which are keyboard entries that have names and descriptions.
    • Also provides methods for listing all the active shortcuts as well as allowing a shortcut to be rebound (for instance, if you were to allow the user to choose a key for a shortcut).
    • Added a change event to Keyboard.manager whenever any keyboard is activated.
  • Tips:
    • NEW Tips option “windowPadding” allows you to reduce or expand the virtual size of the window for tip positioning. Defaults to {x:0, y:0}. You can use that is a workaround for the scrollbars not being considered when calculating tip positions.
  • HtmlTable:
    • fixed numerous bugs filed in Lighthouse
    • HtmlTable can no longer apply it’s click behavior more than once.
    • HtmlTable now pushes headers defined in the options.
    • Reworked HtmlTable’s DOM a bit to allow for positioning of the sort icon
    • Added new set method for headers and footers.
    • Fixed error in HtmlTable.Parsers when sorting by date. format(‘db’) was being applied to the text and not the date object.
  • Array:
    • Added Array.shuffle
  • Request.JSONP:
  • Fx.Slide:
    • Added an option to specify the wrapper element for Fx.Slide. Was already present in the docs but could not be passed as an option.
  • Mask:
    • Added options for the IframeShim for Mask

Download it with the MooTools More builder.

As usual, if you find any issues, file a ticket at lighthouse. There are already tickets open for 1.2.4.4 that we are not including fixes for in this release. Look for a release for these things in the next few weeks.

MooTools Depender - A Build Tool for MooTools JavaScript Libraries

Written By Aaron Newton, on Monday, November 9th 2009, 2:10pm

As mentioned in the new features in MooTools More in 1.2.4.1, there’s a new plugin called Depender which uses MooTools dependency mappings to allow you to lazy load additional scripts on the fly based on what you need. Rather than list every single file you depend on, you just list the features you want to use and it computes all the specific files needed and each of the files that they need (and so on), excludes the files you already have, and then injects the remaining scripts into the document, providing a callback.

Unfortunately this method is rather slow. The JavaScript plugin must inject each individual script in the dependency list and all these requests can only go as fast as your browser can make them. As a companion to this plugin, we have also authored a stand alone server side application.

New Server-Side Depender

The new server-side depender companion app ships in two forms: a PHP version and a Django version. They each have their own positives and negatives. The PHP version ships with a web-based interface — a builder you can use to check off the things you want in your download (similar to what you see on MooTools.net). On the other hand, the Django version is faster. The Django app caches everything to memory but the PHP version caches results to disk.

Depending on your needs, you can also use these server-side applications to lazy load chunks of functionality on the fly. This obviously requires your application to talk directly to the server when it needs more code. These apps aren’t designed for enterprise scale.

The server side applications are available on github. We still consider the state of this project to be beta, but we want to get the tools into your hands now. If you have any feedback or find any bugs, we want to hear about it. Check out the documentation to see how it all works, including the Depender Client(docs), which gives you this nifty interface:

    Depender.require({
            scripts: ['DatePicker', 'Logger'], //array or single string for one item
            callback: function() {
                    //your code that needs DatePicker and Logger
            }
    });
    //later, you need to load more dependencies...
    Depender.require({
            scripts: 'Fx.Reveal', //array or single string for one item
            callback: function(){
                    //if, for some reason, Fx.Reveal is available already,
                    //then this function will execute immediately, otherwise it will
                    //wait for the requirements to load
                    $('someElement').reveal();
            }
    });

Libraries that you download with Depender will all have a standard header that looks something like this:

    //MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2009 Valerio Proietti, <http://mad4milk.net>, MIT Style License.
    //MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.
    //Contents: Core, Browser, Array, Function, Number, String, Hash, Event, Class, Class.Extras, Element, Element.Event, Element.Style, Element.Dimensions, Selectors, DomReady, JSON, Cookie, Swiff, Fx, Fx.CSS, Fx.Tween, Fx.Morph, Fx.Transitions, Request, Request.HTML, Request.JSON, More, Element.Shortcuts, Element.Measure, Fx.Reveal
    //This lib: http://clientcide.com/js/build.php?requireLibs=mootools-core&require=Fx.Reveal&compression=none

This header includes, among other things, a manifest of the contents of the file and a url that can be used to retrieve it again. This is especially useful if you want to come and download the file again for the latest version.

The builder on MooTools.net does not use Depender yet but we will deploy it there soon. You can see it live on the Clientcide builder.

MooTools More 1.2.4.2

Written By Aaron Newton, on Tuesday, October 27th 2009, 2:50pm

There’s nothing like releasing code to uncover glitches. Since last week’s release of MooTools Core 1.2.4 and MooTools More 1.2.4.1, there have been a few bugs reported and we wanted to get the fixes out to you as quickly as possible. Most of these are minor. We have unit tests for all the classes we release, but writing a test for every possible configuration is tough, and it’s the real world that sees these features used in ways we can’t imagine.

Today’s release offers no new features, a lot of very minor fixes (to docs and the like), and the restoration of a few changes to the API that weren’t intended (Tips and Fx.Slide, in particular).

(more…)

MooTools 1.2.4

Written By Aaron Newton, on Monday, October 19th 2009, 5:41pm

It’s been three months to the day since the last point release of MooTools and we’re excited about all the goodness packed into this release. At this point, the 1.2 codebase has a very stable API, and our current plan is to release these point releases every three months or so until the 2.0 codebase is online. If we find any serious bugs, though, we’ll be sure to get fixes into your hands as fast as we can.

(more…)