Skip to content

Example usage

Tim Branyen edited this page Jan 15, 2013 · 1 revision

This example renders a View into a template which is injected into a layout.

Defining the layout and template

These example templates are defined using a common pattern which leverages how browsers ignore <script></script> contents when using a custom type attribute.

Note: This is how LayoutManager expects templates to be defined by default (using script tags).

Main Layout

<script id="main-layout" type="layout">
  <section class="content"></section>

  <!-- Login template below will be injected here -->
  <aside class="secondary"></aside>
</script>

Login Template

<script id="login-template" type="template">
  <form class="login">
    <p><label for="user">Username</label><input type="text" name="user"></p>
    <p><label for="pass">Password</label><input type="text" name="pass"></p>
    <p><input class="loginBtn" type="submit" value="Login"></p>
  </form>
</script>

Structuring a View

Each View can associate a template via the template property. This name by default is a jQuery selector, but if you have a custom configuration this could potentially be a filename or JST function name.

Note: If you do not specify a template LayoutManager will assume the View's render method knows what it's doing and won't attempt to fetch/render anything for you.

var LoginView = Backbone.Layout.extend({
  template: "#login-template"
});

If you would prefer to use Backbone.View as your construct, you can simply add the manage: true assignment to your View:

var LoginView = Backbone.View.extend({
  manage: true
});

Alternatively, you can globally configure this (Recommended):

Backbone.Layout.configure({
  manage: true
});

Note: The manage property has been designed to make it possible to mix between LayoutManager specific and non-specific Views.

Create a layout

This code typically resides in a route callback.

var main = new Backbone.Layout({
  template: "#main-layout",

  // In the secondary column, put a new Login View.
  views: {
    ".secondary": new LoginView()
  }
});

Adding a layout to the DOM

To add a layout into the page, simply inject it into a container at the time of creation. Do not call empty().append() more than once for a layout element, unless you detach it first. This is not recommended as it may cause a flicker during re-rendering. It's cleaner and more efficient to only create a layout when you need it and insert into the DOM at that time.

// Use same layout as created above.

// Attach Layout to the DOM.
main.$el.appendTo(".some-selector");

// Render the Layout.
main.render();