O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Views and Templating

Views are the interface to your application; they’re what the end user actually interacts with and sees. In our case, views are logicless HTML fragments managed by the application’s controllers, which deal with event handlers and interpolating data. This is where it can be quite tempting to break the MVC abstraction by including logic directly into your views. Don’t succumb to that temptation! You’ll end up with senseless spaghetti code.

One of the biggest architectural changes you’ll have to make when moving server-side applications to the client side is with views. Traditionally, you could just interpolate server-side data with HTML fragments, creating new pages. However, views in JavaScript applications are somewhat different.

First, you have to transfer any data needed for the view to the client because you don’t have access to server-side variables. This is generally done with an Ajax call, returning a JSON object, which is then loaded by your application’s models. You shouldn’t be prerendering any HTML on the server side, but rather delegating all of that to the client. This will ensure that your client-side application isn’t reliant on the server for rendering views, keeping its interface snappy.

You then load that data into your views, either by creating the DOM elements dynamically with JavaScript or by using templates. I’ll elaborate on those two options below.

Dynamically Rendering Views

One way to create views is pragmatically via JavaScript. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required