Ian Storm Taylor

Co-founder @ Segment.io

Assigning Backbone Subviews Made Even Cleaner

After my post about rendering subviews in Backbone.js, Tim Branyen asked me if I had taken a look at Layout Manager because it aims to solve a lot of the problems that crop up with managing complex application layouts. I’ll be honest, I had seen it referenced a bunch but hadn’t really delved into the source.

But there’s some cool stuff in there. One thing I noticed was that Layout Manager’s setView was really similar to the assign helper I came up with. Except setViews has a much nicer syntax than assign does for render multiple subviews at once.

So obviously—being the slightly OCD designer type that I am—I had to update the API to assign. Here’s what the old one looked like:

render : function () {
    this.$el.html(this.template());

    this.assign(this.subview, '.subview');
    this.assign(this.anotherSubview, '.another-subview');
    this.assign(this.yetAnotherSubview, '.yet-another-subview');
    return this;
}

And here’s the new one:

render : function () {
    this.$el.html(this.template());

    this.assign({
        '.subview'             : this.subview,
        '.another-subview'     : this.anotherSubview,
        '.yet-another-subview' : this.yetAnotherSubview
    });
    return this;
}

Way less verbose when you need to render more than one subview! Don’t know why I didn’t think of that in the first place. Here’s what it does:

assign : function (selector, view) {
    var selectors;
    if (_.isObject(selector)) {
        selectors = selector;
    }
    else {
        selectors = {};
        selectors[selector] = view;
    }
    if (!selectors) return;
    _.each(selectors, function (view, selector) {
        view.setElement(this.$(selector)).render();
    }, this);
}

If you’re looking for more Backbone reading, you should definitely check out the Layout Manager source. Even if it’s just to get ideas for your own augmentations to Backbone.