Cleaning up Boilerplate Backbone Views

Casey Justus JavaScript Leave a Comment

Attention: The following article was published over 10 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

“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, [email protected]

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments