Skip to content

Properties and Methods

leehankyeol edited this page Nov 27, 2015 · 17 revisions

These methods pertain to Backbone.Layout and all managed Backbone.View instances (see setupView).

// Class methods only exist on Layout.
Backbone.Layout.configure({ el: false });

// You cannot do this.
Backbone.View.configure({ el: false });

Instance

Use these methods on an instance of Backbone.Layout or managed Backbone.View.

Quick access: afterRender cleanup constructor getView getViews insertView insertViews remove removeView render renderViews setView setViews then useRAF

afterRender()

If this method is defined, it will be invoked with the layout as its context after every render operation and before the afterRender event is triggered.

cleanup()

If this method is defined, it will be invoked with the layout as its context whenever the layout undergoes a remove operation.

constructor([options])

Accepts an optional options object to be passed to setupView and the Backbone.View constructor.

This method contains the logic that allows Backbone.Layout to be automatically managed by LayoutManager. When you initialize a new Layout, the constructor will call setupView to manage and then call the default Backbone.View constructor.

// Create a new Backbone.Layout, this calls the constructor automatically.
var myLayout = new Backbone.Layout();

// Optionally with options.
var myLayout = new Backbone.Layout({ template: "someTemplate" });

getAllOptions()

Accepts no arguments.

This method is a convenience function that attempts to merge all places that options can end up on into a single location. For instance if you add an option during definition, the options end up on the instance. If you define options during invocation, they end up in the instance options object.

var options = myLayout.getAllOptions();

// Get the template property no matter where it was set on myLayout.
options.template;

getView([fn])

Accepts a variety of arguments, documented below.

This method will get a nested View from a Layout. You have several ways of filtering the nested Views to get the exact View you are looking for. Internally calls getViews and returns the first result.

Function

If you wish to do a complicated lookup for the View, you can pass a filter function.

// This will search through all nested Views and return the first with an active class.
var activeView = myLayout.getView(function(nestedView) {
  // Find the first item that matches the condition.
  if (nestedView.$el.is(".active")) {
    return nestedView;
  }
});
String

If you are just looking for the View that matches a selector you can pass the string selector instead.

// Find the nested View set into the sidebar class.
myLayout.getView(".sidebar");
Object

If you are looking for a View, but only know a specific property on it, you can pass an object that contains the key and value to make a match. This is most commonly used when you have a model and want to find the View that has rendered that model so you can do something to it.

// Remove the View that rendered someModel.
myLayout.getView({ model: someModel }).remove();

getViews([fn])

Accepts the same arguments as getView.

This method will always return a wrapped underscore array even if only a single View is found. It is wrapped so you can chain off it with underscore array methods.

// Remove all nested Views in the users class.
myLayout.getViews(".users").each(function(nestedView) {
  nestedView.remove();
});

// If you want a JavaScript array, call value().
var nestedUserViews = myLayout.getViews(".users").value();

insertView([selector], view)

Accepts an optional selector and a required View.

This is a shortcut method that wraps setView and passes the insert argument as true.

// Insert the FooterView into the footer element, maybe replacing a previous view on that element.
myLayout.insertView("footer", new FooterView());

// Lets say FooterView *is* the footer element, you can simply insert into the parent.
myLayout.insertView(new FooterView({ tagName: "footer" }));

insertViews(views)

Accepts either an array of Views or an object with a selector: view(s) mapping.

If you pass an array of Views these will be automatically appended into the parent. If you pass an object all single Views will be automatically converted to insert mode.

// These Views will be appended per the insert configuration method.
myLayout.insertViews([new HeaderView(), new ContentView(), new FooterView()]);

// If you wanted to append them into specific regions, use an object.
myLayout.insertViews({
  // Single Views are automatically converted to arrays.
  "header": new HeaderView(),

  // So this isn't required here, it's useful for multiple Views though.
  "section": [new ContentView()],

  "footer": new FooterView()
});

remove()

This method will call cleanViews and will internally remove the parent association (allowing garbage collection). After calling those methods it will call the default Backbone.View remove method.

removeView([fn])

Accepts the same arguments as getView.

Internally it passes that value to getViews. It then iterates over the Views found and internally does the equivalent to remove, except it will not call the original Backbone.View remove.

render()

Unlike the traditional Backbone View where you must provide your own custom render method, LayoutManager provides this for you. You can configure the rendering process by providing a custom render method. This is explained in the Configuration documentation.

The return value of a render call is the view itself. If you need to wait until rendering has completed, bind an event handler to the afterRender event. The context of all resolved functions is the View itself.

// Wait until myLayout has finished rendering internally before
// attaching to the page.
myLayout.render().promise().done(function() {
  this.$el.appendTo("body");
});

// Or:
myLayout.render().once('afterRender', function() { 
  myLayout.$el.appendTo("body");
});


// Render and then append to the page, if render is async 
// (fetching templates/async rendering) it will append into 
// the page first.

myLayout.render();
myLayout.$el.appendTo("body");

// Do the above in one line.
myLayout.render().$el.appendTo("body");

renderViews()

This method will render all child views, but not itself. It is useful for chaining off of setViews to render all newly added items. Any chained promise() calls will work as expected (once all child views have re-rendered).

// Attach two different Views in different regions and then render them.
myLayout.setViews({
  "#some_region": new SomeRegion(),
  "#other_region": new OtherRegion()
}).renderViews().promise().done(function() {
  console.log("All views finished rendering.");
});

setView([name], view, [insert])

Accepts an optional selector name, a required View, and an optional insert boolean flag.

If you insert a View it will start being tracked and be available through the getView(s) methods. You can remove it with removeView. If you replace a selector region with a new View, it will automatically clean up the previous View.

The name argument is a selector or any value that can be used by the partial configuration method. By default this is a CSS query selector. If you omit this value, it is assumed you want to use the entire parent and not a specific region of it.

The view is either a Backbone.Layout or a managed Backbone.View. If you pass anything other than this, you will see an exception thrown saying: "Please set View#manage property with selector '?' to true". This indicates you passed either a valid Backbone.View that isn't managed or you passed a completely wrong kind of object.

The insert property determines if the View is replacing all the content within the selector region or simply appending into it. There is an insert configuration method you can override to change this behavior.

// Using all three arguments to insert a NavLinkView into the sidebar.
myLayout.setView(".sidebar", new NavLinkView(), true);

// Appending into the parent.
myLayout.setView(new FooterView(), true);

// Replacing the header with a new View.
myLayout.setView("header", new HeaderView());

setViews(views)

Accepts an object that contains a selector: views mapping.

This is a very useful way of setting multiple nested Views on a parent View. If the value in the mapping is an array those Views will be inserted using insertView, otherwise setView is used.

Lets say you need to set the contents of a header, a few links inside a sidebar, and a footer.

myLayout.setViews({
  // This header will be directly set.
  "header": new HeaderView(),

  // These will be appended.
  ".sidebar": [new NavItemView(), new NavItemView(), new NavItemView()],

  // Don't want to use the element generated by Backbone for this one.
  "footer": new FooterView({ el: false })
});

then(fn)

Accepts a function to call when the rendering has completed.

This allows much nicer chaining from the render function, which returns the Layout instance.

myLayout.render().then(function() {

});

useRAF = true|false

By default this is true, because it offers better performance when rendering. You can set this property to false to enable synchronous rendering.

Class

Use these methods, when you are augmenting LayoutManager or an arbitrary View.

Quick access: cache cleanViews configure setupView

cache(path, [contents])

A hybrid getter/setter method. If you provide only a path string it will act as a getter. If you provide both a string path and template contents (any defined type) it will cache them internally. This is one way to inject templates into LayoutManager dynamically.

// To store a template called: mytemplate.
Backbone.Layout.cache("mytemplate", _.template("<%= hello %>"));

// Fetching that same template.
var mytemplate = Backbone.Layout.cache("mytemplate");

// Referencing in a Backbone.Layout.
Backbone.Layout.extend({
  template: "mytemplate"
});

cleanViews(views)

Accepts a single View or an array of Views. Will loop through every View passed and...

  • Unbind all events on the View.
  • Unbind events from any model or collection properties that have the View as the context.
  • Call stopListening which is a new Backbone 0.9.9 method which will automatically unbind all listenTo events called from the View.
  • Call an optional cleanup method on the View to further clean up.

This is a very useful for when you are finished with a View and want to ensure no lingering effects will happen once it's removed. LayoutManager calls it automatically for you, this is exposed in case you are operating outside of a Layout.

// Clean a single View.
Backbone.Layout.cleanViews(existingView);

// Clean out several Views.
Backbone.Layout.cleanViews([existingView1, existingView2]);

configure(options)

This method accepts an options object that will apply to all View's managed by LayoutManager. Two properties in the options object are special: manage and el.

These options may also be set at extend and invocation as well.

// Extend.
Backbone.View.extend({
  manage: true
});

// Invocation.
new Backbone.View({ manage: true });
  • manage is set to true, LayoutManager will take over and manage all new View instances.
  • el is set to false. LayoutManager will automatically call setElement on the children inside of all newly created View's, unless you provide a value to el on a specific View.

setupView(views, [options])

Accepts a single View or an array of Views and optionally an options object. These options are the same that you would pass when creating a new View. This method will modify a Backbone.View to work with LayoutManager. This is a manual method to do it instead of passing manage: true to configure.

// Create a normal View.
var MyView = Backbone.View.extend({});

// Initialize an instance.
var myView = new MyView();

// Give it superpowers.
Backbone.Layout.setupView(myView);
Something went wrong with that request. Please try again.