Repository navigation
Creating Batman.Views
This guide is about how to create custom Batman.View subclasses to abstract and package JavaScript logic surrounding a user's interaction with your page.
The basic flow of interactions with a Batman application is this: a user triggers an event, which dispatches a route, which routes to a controller action, which gets executed, which renders a template. The template is an HTML file in the app/views folder with the same name as the action being executed. These templates leverage the power of the Batman view binding system using data-bind and kin to display some data to the user and prompt them for the next event.
The controller does all this by instantiating a new Batman.View, setting its html property to the contents of the template, and telling the view to render(). When the view's html property is set, the view inserts it into it's node, and when render is called, it traverses that HTML to find and create your bindings. A vanilla Batman.View instance's render function does this by instantiating a new Batman.Renderer and asking it to do its magic on the view's html. The view then emits a ready event and then sits around waiting for the user to do something.
Batman.Views have another purpose however: they can be used to create reusable, configurable components which can then be created and reused inside the templates. Examples include a Google Maps component, perhaps a lightbox, a segmented button control, or maybe a class to manage the interactions around flash messages. The flow with these Views is different: they aren't instantiated by controller, but instead by the template using a data-view binding. They are subclasses of Batman.View which enhance the standard functionality to do something useful. Lets look at some examples of how developers might use data-view:
<!-- You might want to use a View to make flash messages. This one might apply some CSS styles to make the message clearer to the user, or use some JavaScript to add a close button which hides the div -->
<div data-view="FlashMessageView">Order successfully saved!</div>
<!-- You might want to use a View instead of CSS3 nth-child selectors to apply some styles to round the corners of the the first and last list items in this <ul> to make it look like a nice segmented button -->
<ul data-view="SegmentedButtonView">
<li>Rounded</li>
<li>Not rounded</li>
<li>Rounded</li>
</ul>
<!-- You might want to implement the placeholder attribute of inputs in a View which might detect if the code is running in a browser which doesn't support placeholder and polyfills the functionality if so -->
<input data-view="PlaceHolderInputView"></input>Each of these doo-dads implements some handy functionality which the template can pull in where ever it likes to spice up the experience. FlashMessageView, SegmentedButtonView, and PlaceHolderInputView are all Batman.View subclasses which have some custom code in them which does cool stuff to whatever node they are applied to. The basic flow for implementation is this:
- Create a
Batman.Viewsubclass in a namespace where your view can find it - Override the
renderfunction to do something useful and callsuper - Add useful functions for controlling the views behaviour externally or to be attached as event handlers
- Reference the view using a
data-viewbinding on a node elsewhere.
Let's look at how this flow applies to a couple examples.
FlashMessageView is a View subclass we apply to ephemeral messages meant for display and then dismissal. Let's say the class has two responsibilities: applying some fun styles to make the whatever node it wraps flash-y, and also adding a close button to the node to let users hide it once they have read the message.
For demonstration we'll use jQuery to implement the guts of the view. If we were using only jQuery in this project, we might implement this same functionality by giving our node a unique ID or class, and then using jQuery somewhere to select it and add teh classes and close button. With Batman, the selection step is done for us, and all we have to do is apply the functionality. Your Batman.View will receive a node it is to wrap, so it can be found in in the node property on the view instance.
class FlashMessageView extends Batman.View
constructor: ->
super
@get('node') #=> DOMElementSo, let's apply some jQueries to the node to accomplish the useful stuff. The first idea is to apply these enhancements when the view is created:
class MyApp.FlashMessageView extends Batman.View
constructor: ->
super # process arguments and stuff
node = $(@get('node'))
# Add our flash box classes
node.addClass('flash box warning')
# Create a button and append it
button = $("<button>X</button>")
node.append(button)
# Tell the button to hide the flash box when it's clicked.
button.on 'click', ->
node.hide('fast')That's a Batman.View!
There are a couple things we need to change with this. First, applying the logic in the constructor isn't the best idea. I deceived you: my apologies. Instead, it should be in the overridden render function on the View. This is better because, perhaps unbeknownst to you, Batman.Views should be instantiable without a node. Because the node might not always be available upon construction, construction and rendering are two separate happenings on a View. We put the logic in an overridden render method on the View subclass so that it runs when the node exists and we have a reference to it.
Note: this function must call super. Calling super is important because the behaviour from the super class still needs to happen. Imagine the flash message had a binding in it:
<div data-view="FlashMessageView">
Order #<span data-bind="order.number"> saved successfully!
</div>The super implementation will set up any bindings within the view's HTML, that is to say the HTML which is within the node where data-view occurs. super also fires the view's ready event, which is critical.
So, FlashMessageView should look like this:
class MyApp.FlashMessageView extends Batman.View
render: ->
node = $(@get('node'))
# Add our flash box classes
node.addClass('flash box warning')
# Create a button and append it
button = $("<button>X</button>")
node.append(button)
# Tell the button to hide the flash box when it's clicked.
button.on 'click', ->
node.hide('fast')
super # Call super last to pass up the return valueAnd that's it!
GoogleMapsView is a view which will show a map from Google's Maps API. The biggest difference with this view is that we need to tell the View exactly what area of the earth to show to the user. It's functionality relies on being configured: it has to know something more than just the node it should display within.
The way to do this is by configuring an instance of the GoogleMapsView inside the controller, and then referencing that instance with data-view in the template. For simplicity's sake we'll have the view use the static image API from Google Maps which makes things really easy. This API just returns images for a latitude and longitude given a zoom, width, and height. So, we'll make our View class take those as properties, and then stick them in the src for an <img> tag.
class MyApp.GoogleMapsView extends Batman.View
@accessor 'imageSrc', ->
"http://maps.googleapis.com/maps/api/staticmap?center=#{@get('latitude')},#{@get('longitude')}&zoom=#{@get('zoom')}&size=#{@get('width')}x#{@get('height')}&sensor=false"
render: ->
img = $('<img>').attr('src', @get('imageSrc'))
$(@get('node')).append(img)
trueSo, when this View subclass is instantiated, it expects to be given latitude, longitude, zoom, width, and height properties like so:
# Inside some controller
@set 'currentAddressView', new MyApp.GoogleMapsView
latitude: 45.429197,
longitude: -75.690237
zoom: ...
width: ...
height: ...and then referenced in some template like so:
<h3>Current Address</h3>
<div data-view="currentAddressView"></div>When the <div> above is rendered, the render function on the currentAddressView will be called, which will insert the image into the DOM using the configured options.
In an effort to make the the View a touch more reusable, you could also pull out the configuration options from the HTML itself:
<h3>Current Address</h3>
<div data-view="GoogleMapsView" data-latitude="..." data-longitude="..." ...></div>and then pull out those configuration options in the view's logic:
class MyApp.GoogleMapsView extends Batman.View
@accessor 'imageSrc', ->
"http://maps.googleapis.com/maps/api/staticmap?center=#{@get('latitude')},#{@get('longitude')}&zoom=#{@get('zoom')}&size=#{@get('width')}x#{@get('height')}&sensor=false"
render: ->
node = $(@get('node'))
# Pull out configuration from the DOM if the node has a `data-longitude` attribute for jQuery to look at.
if node.data('longitude')
for key in ['latitude', 'longitude', 'zoom', 'width', 'height']
@set key, node.data(key)
img = $('<img>').attr('src', @get('imageSrc'))
node.append(img)
superNotice that in the first example, data-view referenced an already existing instance of the subclass, and in the second, data-view references the subclass itself such that it creates its own instance.
And thats it!
View instances also have handy callbacks which let you add logic at certain points. Define these functions on your view to have them called.
-
someViewInstance.awakeFromHTMLis called when the view is done rendering and about to be inserted into the DOM. -
someViewInstance.viewWillAppearis called before each time the view is about to be shown, including the first time it's inserted into the DOM, and each time it's shown after being hidden in the future. -
someViewInstance.viewDidAppearis called after each time the view has been shown -
someViewInstance.viewWillDisappearis called before each time the view is about to be hidden -
someViewInstance.viewDidDisappearis called after each time the view has been hidden
A couple notes:
- Views can specify their
htmlin their class bodies:
class CloseButtonView extends Batman.View
html: '<button><img src="/images/close.png"></button>- Views can obliterate their node's contents before rendering with a
Batman.DOM.setInnerHTML @get('node'), "" - Views have access to the render context, stored in the
contextproperty on the view instance.
class CloseButtonView extends Batman.View
render: ->
super
@set 'something', @context.get('some.key.path')Be careful using the above strategy for passing Views data: they should be told their data instead of having to fetch it themselves in the interest of being loosely coupled and thus reusable.
And thats it!