Cleaning up Boilerplate Backbone Views

Casey Justus JavaScript Leave a Comment

“And you think you’re so clever and classless and free.” ― John Lennon

One common complaint developers have with Backbone is the proliferation of repetitive boilerplate code. How many Backbone apps have a view like this declared over and over?

var MyView = Backbone.View.extend({
	el: '#someId',

	template: _.template($("#myTemplate").html()),

	model: myModel,

	render: function() {
    	this.$el.html( this.template( this.model.toJSON() ) );
    	this.stickit();
    	return this;
	}
});

This isn’t a problem inherent with Backbone, but a problem with developers writing repetitive boilerplate code.

One possible solution is to use one of the opinionated frameworks that extend Backbone like Marionette, Chaplin, or Thorax. These are perfectly acceptable solutions if you like how they go about it. They aren’t always necessary though. Instead of extending all views from Backbone.View, do it once for a given model and extend all other views for that model from these view constructors.

var MySubView = MyView.extend({
	el: '#someOtherId',
	template: _.template($("#anotherTemplate").html());
});

This way, I only change the methods that need to be changed. Also note that I’m using backbone.stickit in my render. This will be in all my views for this, but if I don’t have a binding method, it will be a noop. This is the kind of flexibility I get without having to rewrite a big ugly render method, unless of course I need to write a different render method.

var MySubView = MyView.extend({
	el: '#someOtherId2',
	template: _.template($("#anotherTemplate2").html()),
	render: function() {
    	this.$el.html( this.template( this.model.toJSON() ) );

    	var anotherView = new AnotherView().render();
    	var anotherView2 = new AnotherView2({
    		model: someOtherModel;
    	}).render();

    	return this;
	}
});

This is how I would create a hierarchy of views, but for any of the terminal views like AnotherView(), I would extend this from MyView.

This is the beauty of JavaScript’s prototypal inheritance. Objects inherit from other objects. Just like in classical inheritance I can add methods, but I can just as easily change them.

— Casey Justus, asktheteam@keyholesoftware.com


About the Author
Casey Justus

Casey Justus

Casey Justus is a 15-year veteran full stack developer. As an avid open source advocate, he has made contributions to jQuery Mobile and Lobano. The user group he co-founded, upFront, is one of the largest user groups in the midwest and focuses on front-end web development technologies. When he’s not coding he can be found spending time with his amazing wife and daughter, Jennifer and Kessler.


Share this Post

Leave a Reply