Controller provides URL-based same-page routing using HTML5 history (pushState
) or the location hash, depending on what the user's browser supports.
This makes it easy to wire up route handlers for different application states while providing full back/forward navigation support and bookmarkable, shareable URLs, all handled entirely on the client.
If you've used a server-side routing framework like Express or Sinatra, Controller will look very familiar to you. This is no accident!
Getting Started
To include the source files for Controller and its dependencies, first load the YUI seed file if you haven't already loaded it.
<script src="http://yui.yahooapis.com/3.4.0/build/yui/yui-min.js"></script>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the YUI().use()
method.
YUI will automatically load any dependencies required by the modules you
specify.
// Create a new YUI instance and populate it with the required modules. YUI().use('controller', function (Y) { // Controller is available and ready for use. Add implementation // code here. });
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global object.
URL-based Routing on the Client?
You bet! URLs are an excellent way to maintain state in a web app, since they're easy to read, easy to change, and can be bookmarked and shared.
Server-side web frameworks use URLs to maintain state by routing them to different pages and by storing information in query strings. These same techniques can now be used by client-side web apps to achieve better parity with server-side logic and to provide a more seamless user experience.
Controller allows you to define routes that map to callback functions. Whenever the user navigates to a URL that matches a route you've defined, that route's callback function is executed and can update the UI, make Ajax requests, or perform any other necessary actions. See Routing for more details on how this works.
Often you'll want to change the URL in order to trigger a route handler, perhaps because the user has taken an action that should change the state of your application. Controller provides a save()
method that sets a new URL and saves it to the user's browser history. There's also a replace()
method to replace the current URL in the user's browser history without creating a new entry. The Updating the URL section describes these methods in detail.
Sample URLs
In browsers that support the HTML5 history API, Controller generates real URLs that can gracefully degrade to allow server-side handling of initial pageviews or pageviews without JS enabled. Most modern browsers (including recent versions of Firefox, Chrome, Safari, and Mobile Safari) support HTML5 history.
In browsers that don't support the HTML5 history API, Controller falls back on using the location hash to store URL information and trigger history changes. This mostly applies only to older browsers and Internet Explorer. Unfortunately, even Internet Explorer 9 doesn't support the HTML5 history API.
The table below contains examples of the kinds of URLs Controller might generate when the save()
method is called on a Controller instance, starting from an initial URL of http://example.com/
.
Code | HTML5 URL | Legacy URL |
---|---|---|
controller.save('/') |
http://example.com/ |
http://example.com/#/ |
controller.save('/pie/yum') |
http://example.com/pie/yum |
http://example.com/#/pie/yum |
controller.save('/pie?type=pecan&icecream=true') |
http://example.com/pie?type=pecan&icecream=true |
http://example.com/#/pie?type=pecan&icecream=true |
Using Controller
Instantiating Controller
To begin adding route handlers, the first thing you'll need to do is create a new Controller instance.
var controller = new Y.Controller();
This is the simplest way of working with Controller, but you may also extend Y.Controller
to create a custom Controller class that suits your needs. The Extending Y.Controller
section explains how to do this.
Config Properties
When instantiating Controller, you may optionally pass in a config object containing any of the following properties. For more details on these properties, see Controller's API docs.
Property | Default | Description |
---|---|---|
root |
'' |
Root path from which all routes should be evaluated. See Setting the Root Path for details. |
routes |
[] |
Array of route objects specifying routes to be created at instantiation time. This can be used as an alternative to adding routes via the Each item in the array must be an object with the following properties: |
Here's an example that sets all the configurable properties:
var controller = new Y.Controller({ root: '/mysite', routes: [ {path: '/', callback: function () { alert('Hello!'); }}, {path: '/pie', callback: function () { alert('Mmm. Pie.'); }} ] });
Read-Only Properties
Controller instances currently expose a single informational property, html5
, which is meant to be read-only.
Property | Description |
---|---|
html5 |
Whether or not the user's browser is capable of using HTML5 history. This property is for informational purposes only. It's not configurable, and changing it will have no effect. |
Setting the Root Path
Let's say the URL for your website is http://example.com/mysite/
. Since Controller matches routes based on the URL path, it would look for routes beginning with /mysite/
.
You could deal with this by ensuring that all your routes start with /mysite/
, but that's tedious, and it won't work well if you're writing a component that might be used on various sites where you can't anticipate the root path.
This is where the root
config property comes in. If you set root
to '/mysite'
, then all routes will be evaluated relative to that root path, as illustrated below.
The root
must be an absolute path.
URL | Route (No root) | Route (Root: /mysite) |
---|---|---|
http://example.com/mysite/ |
/mysite/ |
/ |
http://example.com/mysite/pie/ |
/mysite/pie/ |
/pie/ |
http://example.com/mysite/ice-cream/yum.html |
/mysite/ice-cream/yum.html |
/ice-cream/yum.html |
Extending Y.Controller
While Y.Controller
may be instantiated and used directly, you might find it more convenient to extend the Y.Controller
class to create a subclass customized for your particular needs.
Use the Y.Base.create()
method to extend Y.Controller
and add or override prototype and static members. You may also optionally specify one or more Base extensions to mix into your new class.
// Create a Y.CustomController class that extends Y.Controller. Y.CustomController = Y.Base.create('customController', Y.Controller, [], { // Add or override prototype properties and methods here. }, { // Add static properties and methods here. });
One benefit of extending Y.Controller
is that you can easily add default config properties, routes, and route handlers to the prototype of your custom Controller class, and they'll be shared by all instances of that class unless overridden at the instance level:
Y.CustomController = Y.Base.create('customController', Y.Controller, [], { // Evaluate all routes relative to this root path. root: '/mysite', // Share these default routes with all CustomController instances. routes: [ {path: '/', callback: 'index'}, {path: '/pie', callback: 'pie'} ], // Default route handlers inherited by all CustomController instances. index: function (req) { // ... handle the / route ... }, pie: function (req) { // ... handle the /pie route ... } }); // Create a CustomController instance that inherits the defaults and adds to // them. var controller = new Y.CustomController(); controller.route('/cheesecake', function (req) { // ... handle the /cheesecake route });
Now all instances of Y.CustomController
will inherit all the custom defaults and can add to or override them. The controller
instance created here will handle the /
and /pie
routes in addition to its own /cheesecake
route, and will evaluate all routes from the /mysite
root path.
Routing
Use the route()
method to add a new route to a Controller instance. The first parameter is a path specification or regular expression that the URL path must match, and the second parameter is a callback function or function name to execute when the route is matched.
var controller = new Y.Controller(); // Add a route using a string as the path specification. controller.route('/pie', function () { Y.log('You visited http://example.com/pie'); }); // Add a route using a regular expression as the path specification. controller.route(/^\/cake$/, function () { Y.log('You visited http://example.com/cake'); });
Routes are always evaluated in the order they're added. The first route that matches a given URL is executed, and any subsequent routes that also match the URL will not be executed unless the first route passes control to the next route. See Chaining Routes for more info on executing more than one route for a given URL.
When a route callback is specified as a string instead of a function, it's assumed to represent the name of a function on the Controller instance.
var controller = new Y.Controller(); controller.pie = function () { Y.log('You visited http://example.com/pie'); }; // Add a route using controller.pie as the route callback. controller.route('/pie', 'pie');
As an alternative to using the route()
method, routes may be added at instantiation time using the routes
config property:
var controller = new Y.Controller({ routes: [ {path: '/pie', callback: function () { Y.log('You visited http://example.com/pie'); }}, {path: /^\/cake$/, callback: function () { Y.log('You visited http://example.com/cake'); }} ] });
This is functionally equivalent to adding the routes via the route()
method, except that the routes are added during the Controller's initialization stage rather than after.
Paths, Placeholders, and RegExps
A route path may be specified as either a string or a regular expression. When a string is provided, it's compiled to a regular expression internally. If the regex matches the path portion (not including protocol, domain, query string, etc.) of a URL being dispatched, the route callback will be executed.
Path strings may contain placeholders. When a route is matched, the values of these placeholders will be made available to the route callback on the req.params
object.
A placeholder prefixed by a :
, like :pie
, will match any character except for a path separator (/
).
controller.route('/pie/:type/:slices', function (req) { Y.log("You ordered " + req.params.slices + " slices of " + req.params.type + " pie."); }); controller.save('/pie/apple/2'); // => "You ordered 2 slices of apple pie." controller.save('/pie/lemon+meringue/42'); // => "You ordered 42 slices of lemon meringue pie."
A placeholder prefixed by a *
, like *path
, will match as many characters as it can until the next character after the placeholder, including path separators.
controller.route('/files/*path', function (req) { Y.log("You requested the file " + req.params.path); }); controller.save('/files/recipes/pie/pecan.html'); // => "You requested the file recipes/pie/pecan.html"
Placeholder names may contain any character in the range [A-Za-z0-9_-]
(so :foo-bar
is a valid placeholder but :foo bar
is not).
When a regular expression is used as a path specification, req.params
will be an array. The first item in the array is the entire matched string, and subsequent items are captured subpattern matches (if any).
controller.route(/^\/pie\/([^\/]*)\/([^\/]*)$/, function (req) { Y.log("You ordered " + req.params[1] + " slices of " + req.params[2] + " pie."); }); controller.save('/pie/maple+custard/infinity'); // => "You ordered infinity slices of maple custard pie."
Route Callbacks
When a route is matched, the callback function associated with that route will be executed, and will receive two parameters:
req
(Object)-
An object that contains information about the request that triggered the route. It contains the following properties:
params
(Object or Array)-
Parameters matched by the route path specification.
If a string path was used and contained named parameters, then
params
will be a hash with parameter names as keys and the matched substrings as values. If a regex path was used,params
will be an array of matches starting at index0
for the full string matched, then1
for the first subpattern match, and so on. path
(String)-
The current URL path matched by the route.
query
(Object)-
Hash of query string parameters and values specified in the URL, if any.
next
(Function)-
A function that will pass control to the next matching route (if any) when called. If not called, no further routes will be executed.
Inside a route callback, the this
keyword will always refer to the Controller instance that executed that route.
Chaining Routes
By default, only the first route that matches a URL will be executed, even if there are several routes that match. However, when a route is executed, it will receive a next()
function as its second parameter. Calling this function will execute the next matching route if there is one.
controller.route('/pie', function (req, next) { Y.log('Callback #1 executed!'); next(); }); controller.route('/pie', function (req) { Y.log('Callback #2 executed!'); }); controller.route('/pie', function (req) { Y.log('Callback #3 executed!'); }); controller.save('/pie'); // => "Callback #1 executed!" // => "Callback #2 executed!"
If you want the first route callback to pass some data along to subsequent callbacks, you can attach that data to the req
object, which is shared between all routes that are executed during a single request.
controller.route('/ice-cream', function (req, next) { req.flavor = 'cookie dough'; next(); }); controller.route('/ice-cream', function (req) { Y.log("I sure do like " + req.flavor + " ice cream."); }); controller.save('/ice-cream'); // => "I sure do like cookie dough ice cream."
Updating the URL
Call the save()
or replace()
methods to update the URL and store an entry in the browser's history.
The only difference between the two is that save()
saves a new history entry, while replace()
replaces the current history entry.
// Save a new history entry. controller.save('/cake'); // Replace the current history entry with a new one. controller.replace('/pie');
Changing the URL in this way will trigger a dispatch, and will execute the first route that matches the new URL (if any). A dispatch will also be triggered automatically whenever the user uses the browser's back or forward buttons.
When you need to provide state information to your route handlers, it's best to provide that information as query parameters in the URL. This way, your application's state is always reflected in the current URL, and can be properly restored when a URL is bookmarked or copied.
controller.route('/ice-cream', function (req) { var flavor = req.query.flavor; if (flavor === 'vanilla') { Y.log('Vanilla? How boring.'); } else if (flavor === 'americone dream') { Y.log('Mmmm, Colbert-flavored ice cream.'); } else { Y.log('Error! Error! Does not compute!'); } }); controller.save('/ice-cream?flavor=vanilla'); // => "Vanilla? How boring." controller.save('/ice-cream?flavor=americone+dream'); // => "Mmm, Colbert-flavored ice cream." controller.save('/ice-cream?flavor=kitten'); // => "Error! Error! Does not compute!"
Capturing Link Clicks
An excellent way to provide progressive enhancement on a page with URLs that can be handled by both the server and the client is to use normal links, and then add a delegated event handler to capture clicks on those links and use client-side routing when JavaScript is available. You can also use this technique to selectively use client-side routing or server-side routing depending on which link is clicked.
// This sample requires the `node-event-delegate` module. YUI().use('controller', 'node-event-delegate', function (Y) { // ... create a controller instance as described in the sections above ... // Attach a delegated click handler to listen for clicks on all links on the // page. Y.one('body').delegate('click', function (e) { // Allow the native behavior on middle/right-click, or when Ctrl or Command // are pressed. if (e.button !== 1 || e.ctrlKey || e.metaKey) { return; } // Remove the non-path portion of the URL, and any portion of the path that // isn't relative to this controller's root path. var path = controller.removeRoot(e.currentTarget.get('href')); // If the controller has a route that matches this path, then use the // controller to update the URL and handle the route. Otherwise, let the // browser handle the click normally. if (controller.hasRoute(path)) { e.preventDefault(); controller.save(path); } }, 'a'); });
Now a click on any link, such as <a href="http://example.com/foo">Click me!</a>
, will automatically be handled by the controller if there's a matching route. If there's no matching route, or if the user doesn't have JavaScript enabled, the link click will be handled normally by the browser.
To Dispatch or Not to Dispatch?
Dispatching is what it's called when Controller looks for routes that match the current URL and then executes the callback of the first matching route (if any).
A dispatch can be triggered in the following ways:
- Automatically, whenever the URL changes after the initial pageview.
- Manually, by calling the
dispatch()
method. - Manually (but only in HTML5 browsers), by calling the
upgrade()
method when the URL contains a hash-based route that was copied from a legacy browser.
It's important to remember that if a user bookmarks or copies an HTML5 URL generated by Controller and visits that URL later, the full URL will be sent to the server. On the other hand, if a user bookmarks or copies a hash-based URL in a legacy browser and then visits it later, the hash portion of the URL won't be sent to the server.
For instance, let's say a user visits your website at http://example.com/
. On that page, you have the following code:
<button id="pie">Click me if you like pie!</button> <script> YUI().use('controller', 'node', function (Y) { var controller = new Y.Controller(); controller.route('/pie', function () { // Show the user a photo of a delicious pie. }); Y.one('#pie').on('click', function () { controller.save('/pie'); }); }); </script>
In an HTML5 browser, when the user clicks the button, Controller will change the URL to http://example.com/pie
and then execute the /pie
route, but the browser won't contact the server. If the user bookmarks this URL and then loads it again later, the web server will handle the request. If it doesn't recognize the path /pie
, it may return a 404 error, which would be no good.
In a legacy browser, clicking the button will cause the URL to change to http://example.com/#/pie
, and the /pie
route will be executed, also without contacting the server. The difference is that if the user bookmarks this URL and loads it later, the hash portion won't be sent to the server. The server will only see http://example.com/
, so it will be necessary to handle the request on the client as well.
There are two ways to deal with this. One way would be to implement server-side logic to handle requests for /pie
and render the appropriate page. To provide fallback support for hash-based URLs, we can modify the client-side code to call the dispatch()
method in legacy browsers, by adding the following:
// Always dispatch to an initial route on legacy browsers. Only dispatch to an // initial route on HTML5 browsers if it's necessary in order to upgrade a // legacy hash URL to an HTML5 URL. if (controller.html5) { controller.upgrade(); } else { controller.dispatch(); }
The benefit of this is that HTML5 URLs will be rendered on the server and won't present any difficulties for search crawlers or users with JS disabled. Meanwhile, hash-based URLs will be handled on the client as long as JS is enabled. The drawback with this method is that it may require maintaining duplicate logic on both the server and the client.
The other way to handle this would be to configure the server to render the same initial page for all URLs (it would essentially route all paths to the same page), and always dispatch on the client, regardless of the browser's capabilities:
// Dispatch to an initial route on all browsers. controller.dispatch();
On the one hand, this solution avoids most of the server-side complexity and keeps all the controller logic on the client. On the other, it requires the client to support JavaScript, so it won't play well with search crawlers that can't run JavaScript or users who disable JavaScript.
Best Practices
HTML5 URLs vs. Hash URLs
As discussed in To Dispatch or Not to Dispatch?, there are benefits and drawbacks to both HTML5 URLs—that is, URLs generated via the HTML5 history API—and hash-based URLs. This adds difficulty to any client-side URL-based routing solution, and unfortunately it means you may need to make some tough choices about the architecture of your application.
The primary benefit of HTML5 URLs is that they can potentially be handled on the server as well as on the client. This has potential benefits for application architecture (rendering an initial pageview on the server is often faster than rendering it on the client) and for preventing link rot (if you rewrite or replace your application at some point, it's relatively easy to set up server-side redirects to point the old URLs to a new location). That said, HTML5 URLs may require more server-side logic in order to work correctly.
Hash-based URLs, on the other hand, can't be handled on the server because browsers don't send the hash portion of a URL to a server. This means they must always be rendered on the client using JavaScript. Even worse, if you eventually rewrite or replace your web app, it's extremely unlikely that you'll be able to keep that old JavaScript around just for the sake of redirecting old URLs, which means any old hash-based URLs in the wild are likely to stop working.
In general, the benefits of HTML5 URLs tend to outweigh the drawbacks when compared to hash-based URLs, which is why Controller automatically defaults to using HTML5 URLs in browsers that support it. The hash-based URLs generated by Controller should be used only as a fallback for legacy browsers.
Cross-browser URL Compatibility
It's very important that any URL generated by Controller be usable in any browser. If a user of a legacy browser copies a URL and shares it with a friend who uses an HTML5 browser, that URL should still work. And if someone copies an HTML5 URL and shares it with a user of a legacy browser, that needs to work too.
When a hash-based URL is loaded in an HTML5 browser and dispatch()
or upgrade()
are called, Controller automatically upgrades the URL to an HTML5 URL. So a URL like http://example.com/#/pie
will become http://example.com/pie
, and the HTML5 browser will execute the appropriate route handler.
The difference between the dispatch()
and upgrade()
methods is that dispatch()
always dispatches to the first route that matches the current URL, whereas upgrade()
will only dispatch if the browser is an HTML5 browser and the URL is a legacy hash-based URL that must be handled on the client in order to upgrade it to an HTML5 URL.
When an HTML5 URL like http://example.com/pie
is loaded in a legacy browser, what happens depends on how your server is configured:
If the server is capable of handling the URL, then it should render the page in the appropriate state, and Controller won't need to do anything.
If the server is not capable of handling the URL, then it should render the initial page state and you should call Controller's
dispatch()
method. Controller will parse the HTML5 URL and execute the appropriate route, even in a legacy browser.
For more on how dispatching works, see To Dispatch or Not to Dispatch?.
Progressive Enhancement and SEO
In general, HTML5 URLs that can be rendered by the server when necessary provide the best support for both progressive enhancement (by rendering initial pageviews more quickly, even in browsers with JavaScript disabled) and for search engine optimization (by allowing you to use real, non hash-based URLs that can be crawled by search bots, which may not support JavaScript).
Being able to render the same application states both on the server and the client may require you to write duplicate code. However, if you use JavaScript on the server, and in particular if you use Node.js, you may be able to share code.
Controller's routing style and route specification format are intentionally very similar to those of the Express.js server-side framework. With a little care, you may be able to use the same route handler code on both the server and the client.
Supporting Google's Ajax Crawling Scheme
One of the problems with the hash-based URLs Controller uses to support legacy browsers is that most search engines don't distinguish between a URL with a hash fragment and one without. This means that, to a search bot, the URLs http://example.com/
and http://example.com/#/pie
might look the same, even though they might represent completely different content in your application.
Google's Ajax Crawling Scheme specifies a way to make hash-based URLs crawlable by the GoogleBot if you're willing to implement some extra server-side logic.
To indicate to the GoogleBot that your hash URLs are crawlable, the hash must be prefixed by #!
instead of the default #
. You can make Controller do this automatically by setting the value of the static Y.HistoryHash.hashPrefix
property before initializing any Controller instances:
Y.HistoryHash.hashPrefix = '!';
Next, read Google's getting started guide for a description of how the Ajax crawling scheme works and the additional changes you'll need to make to your application. Most of the changes you'll need to make will have to happen in your server-side logic.
Don't skip the server-side changes! Without them, using the #!
prefix won't do you any good, and may even hurt the search ranking of your pages.
Known Limitations
HTML5 history is not currently supported by any version of Internet Explorer. This includes Internet Explorer 9 and developer preview releases of IE10 as of the time these docs were written. Please feel free to let Microsoft know how you feel about this.
Android 2.x is forced to use hash-based history due to a bug in Android's HTML5 history implementation. This bug does not affect Android 3.0 and higher.
Hash-based URLs are case-insensitive in Internet Explorer 8 and 9. Most browsers follow the HTML5 spec and treat URLs—including hash-based URLs—as case-sensitive. IE8 and IE9 ignore case in hash-based URLs, so changing a hash-based URL from
/foo
to/Foo
won't trigger a dispatch.Internet Explorer 6 and 7 only retain the most recent hash-based URL from a previous pageview after navigating to another page and returning. However, history entries created within a single pageview will persist for the duration of that pageview, and bookmarked URLs will still work in all cases.
In Internet Explorer 6 and 7, the page titles displayed for history entries in the browser's history dropdown menu are not correct. Instead of showing the title of each page, it shows part of the URL of each page.