Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Scott Rabin, a Front End Technical Lead for Huddler, Inc., a forum platform and media company, and author of The Twitter Flight Edge. When he’s not working on bringing communities together, he’s working on Javascript utility libraries and web-based home theater software.

Using Twitter’s Flight library requires you to break your application down into discrete chunks of functionality as Components. In our last post on custom form validation, we covered the use of mixins to provide common functionality between components and express our application by creating a validation mixin to better describe form inputs. This allowed us to match form inputs to validation functions and keep the component definition simple. In this post, we’ll take the next step and submit forms via AJAX to see how that interaction fits into a component framework.

A Familiar Example

Like form validation, it’d be helpful to have a real example to work with while implementing AJAX-submitted forms. We’ll turn to another ubiquitous form found across the web: the comment form.

twitterflight.2.1

The user experience for this form should be simple and familiar: submit the form and show the newly created comment at the end of the comment list.

Baseline HTML

For the remainder of this blog post, we’ll be working with the following markup. It has a container for our comments, an existing comment, and the form we’ll use to submit new comment:

Our Component Event Interface

When creating components that have specific interactions like our comment form, it’s a common tendency to write a bunch of JavaScript that performs its job and binds it directly to the element in need of that functionality. We could certainly do the same with Flight components here:

  • One component bound to a common ancestor of our comments list and add comment form
  • Delegated events waiting for a submit from the form that will send the data via AJAX
  • Insert the response into the list

After completing this list, our job would be complete. But that’s not very extensible, and it’s certainly not idiomatic Flight.

Instead, we should think about the actions that each component should listen for and what they should do in response. Consider just the comments list for now. It needs to append comments to the end of the container when a new comment is added, and that is its sole responsibility. If we were to translate that requirement directly into a Flight component, we’d end up with something like the following:

It’s not important where the addComment event comes from, just that it happened, and when it does happen, we should add the comment to the end of the list. For now, the only possible source of that event is our new comment form. It should wait for the user to fill it out and submit it, and when the request completes successfully, we’ll know a new comment has been added. Translating that into a component is just as straightforward as the comment list component.

If we left this implementation as-is and wrote a basic server to handle the POST request, we’d have a fully functional comments section where users could submit the new comment form via AJAX and see their new comment appear at the end of the list of existing comments.

twitterflight.2.2

Generalizing Our AJAX Forms

Looking again at our new comment form component, it seems fairly basic. All it does is wait for a form submit, hijack the event to submit via AJAX, and then emit a custom event. If we want to use this type of a component again on another form, we’d have to create another component and manually instantiate it there, too. Instead, let’s try to write a component that handles any form on the page that can be submitted via AJAX. We know at least one of the forms will need to emit a custom event (in this case, addComment), so our component should be able to handle that case as well.

The only question that remains is how to attach this component to each form on the page. We could write the component as a standalone and attach it to each form, but that would require us to attach the component each time the page markup changes – a burdensome task with repeated code in too many locations. Instead, we’ll attach one instance of the new component to the document element and listen for all form submit elements, filtering only the ones that should be AJAX-ified. We’ll use the implementation of our soon-to-be-defunct AddCommentFormComponent as a template for our generalized AJAX form component, replacing the hard-coded values with attribute lookups on the form being submitted.

All we need to do now is update our markup to add the AJAX success event to our add comment form:

And voila! We have the same functionality as before with the custom AddCommentFormComponent, except we can now just add an attribute to any form element to have it submit via AJAX and emit an event with the response data attached.

As with the form validation mixin from our last adventure with Flight, we’ve separated our application into discrete, highly modular parts that distinguish user input from application-level events. Modifying your approach to application development to break workflows into their composite actions lends itself to flexible, reusable code that can easily integrate with any number of components without adjusting the existing system. In our example, we only update the comments list when a user posts a new comment, but our design allows us to add a polling function that checks for new comments since the last one and triggers the addComment event for each one. We could easily add that feature without changing the CommentsListComponent or the AjaxFormComponent. You can learn more about attaching features to existing component systems in Chapter 5: Data Components and Accessing Remote Data in The Twitter Flight Edge.

Extending the AJAX Component

Forms aren’t the only AJAX-upgradeable elements on a typical web page. Try implementing some of these features to see how Flight helps modularize your user interaction code:
• Display a new page of comments via pagination links
• Display a dialog fetched from the server when the user clicks on a link

Not a subscriber? Sign up for a free trial.

Be sure to look at the Twitter Flight and JavaScript resources that you can find in Safari Books Online.

Safari Books Online has the content you need

The Twitter Flight Edge covers the open source library from Twitter used heavily in their front end JavaScript. It offers a lightweight way to define the behavior of and communication between components, which are well-defined fragments of a page meant for progressive enhancement. This book was written for the curious JavaScript developer who learns new libraries by hacking on examples or personal projects. We walk through developing a simple sample application – an RSS reader – using Twitter Flight and supporting libraries. Everything from basic components like tabs to remote data fetching is covered, highlighting the benefits Flight offers for event-driven applications.
Eloquent JavaScript is a guide to JavaScript that focuses on good programming techniques rather than offering a mish-mash of cut-and-paste effects. The author teaches you how to leverage JavaScript’s grace and precision to write real browser-based applications. The book begins with the fundamentals of programming—variables, control structures, functions, and data structures—then moves on to more complex topics, like object-oriented programming, regular expressions, and browser events. With clear examples and a focus on elegance, Eloquent JavaScript will have you fluent in the language of the web in no time.
Maintainable JavaScript contains JavaScript practices—including code style, programming tips, and automation—and you’ll learn how to write maintainable code that other team members can easily understand, adapt, and extend. Author Nicholas Zakas assembled this collection of best practices as a front-end tech leader at Yahoo!, after completing his own journey from solo hacker to team player.

About the author

scottrabin Scott Rabin is a Front End Technical Lead for Huddler, Inc., a forum platform and media company. When he’s not working on bringing communities together, he’s working on Javascript utility libraries and web-based home theater software, and can be reached at twitterflight@scottrabin.com.

Tags: Ajax, Comment Form, Components, events, Flight Library, Javascript, mixins, Scott Rabin, Twitter Flight,

Comments are closed.