Backbone.COMPOSER

a minimal, slightly opinionated plugin to simplify view rendering and composing complex views

Goals

  • Minimize boilerplate view code
  • Compose complex views with subview management
  • Manage view life cycle to minimize memory leaks
  • Restore the state of the DOM after re-rendering

Common Use Case

Container

Table

Row

Row

Row

Rendering

  • Default render
  • Templating
  • Removing div wrapper
  • Serialize view data
  • Rendering hooks

Render

render: function() {
    if (this.template) {
        this.$el.html( this.template( this ) );
    }
    return this;
},

Default render provided to avoid

  • Also helps with rerendering
  • Can be overridden

Templating

Backbone.View.extend({
  template: JST['templates/index.ejs'],
  ...
});
  • Template must be a function
  • Doesn't provide template loading
  • Use pre-compiled template system

Attach To Template

// view specific
Backbone.View.extend({
  template: JST['templates/index.ejs'],
  attachToTemplate: true,
  ...
});

// globally set
Backbone.View.prototype.attachToTemplate = true;

Avoid dreaded <div> wrapper

Serialize View Data

Backbone.View.extend({
  serializeData: function() {
    var result = this.model.toJSON();
    result.fullName = result.firstName + ' ' + result.lastName;
    return result;
  }
});

#template
<table>
    <tr>
        <td><%= fullName %></td>
    </tr>
</table>

View Manager will use results as input to template rendering

Rendering Hooks

Backbone.View.extend({
  ...
  onRender: function() {
    this.$('#state').select2();
  }
});

fires rendered event and calls onRendered

Subviews

  • Adding
  • Removing
  • Lifecycle
  • Hooks

Adding Sub Views

showItems: function() {
  this.collection.forEach(function(model){
    var view = new ItemView({model: model});
    this.addSubView({
        view: view, 
        selector: 'prepend'
    });
  }, this);
}

addSubView adds a view to a parent view's DOM and manages it

Set View

var container = new Backbone.View({el: '.container'});
var view = new UserView({model: this.model});
container.setView(view);

Use setView to swap the view of a container

Removing

  • removeSubViews - Remove all subviews
  • removeSubViewForModel - Pass a model to remove it's view
  • close - Call close directly on a subview

Subview Hooks

  • onShow - called when added to parent
  • shown event - fired when added to parent
  • onClose - called before removal from parent 
  • closed - fired when removed from DOM

Getting started

bower install backbone.composer

bower

More Information

  • Repo - https://github.com/nnance/backbone-composer
  • Wiki - https://github.com/nnance/backbone-composer/wiki

Shameless Plug

  • Please STAR the project
  • Follow me on Github and @nancenick
Made with Slides.com