(guest@joequery.me)~ $ |

Prevent Backbone events from firing multiple times

I've been diving into Backbone recently. I enjoy working with it, primarily due to how easy the framework is to understand.

But I recently ran into a problem where backbone events were firing multiple times.

The root cause

The ultimate cause of backbone events firing multiple times is that the events are being bound multiple times.

While that may seem obvious, it's important to note since it truly is the essence of the problem.

How can I know for sure if events are being bound multiple times?

The Visual Event chrome plugin is a great way to learn what events are bound to specific DOM elements.

Visual Event

Suppose the event firing multiple times is associated with a form submit. Activate Visual Event, hover over the form, and you might see multiple 'submit' events associated with the form.

Why are events being bound multiple times?

If you take a look at this Stackoverflow Thread, the top answer indicates that events can be bound multiple times when you instantiate the same view multiple times.

The solution: Is your View really new? Creating vs Re-rendering

Understanding when to create a new View instance vs holding on to a previous instance is critical to preventing these multiple binding issues.

Generally, Views are thought of as standalone units. But you might find yourself in a situation where you want a View's action to render a different View. In this situation, you have to ask if you're truly creating a new instance of this View or merely wanting it to render new content.

In my case, I realized that I was instantiating a child View many times within the parent View when I really just wanted the child View to render with different content.

My solution was to create a reference to the child View within the parent View and use that for the entire duration of the parent View.

var ParentView = Backbone.View.extend({
    initialize: function(options){
        this.ChildView = new ChildView();
    }
});

What if my ChildView needs arguments?

A potential issue with the above approach is that you need to create the ChildView instance while creating the ParentView instance. The ChildView might need information passed in through the options, but that data might not be available at the time of the ParentView initialization.

Creating a setter method within the ChildView to accept the data it needs alleviates this issue.

Tagged as javascript

Date published - May 30, 2015