sublime
sublime

Reputation: 4161

Backbone View render function getting called multiple times

I have a view that represents a folder. I have bunch of subviews, that this folder view creates, each representing a unique thumbnail in that folder. It turns out that each one of those subview's render method is getting called multiple times (3). Is there a way to find out how view's render method is called. There are different places which could render a trigger event for e.g., if models metadata is changed. It has become a huge mess and I'm looking for a way to debug backbone view's to know what is exactly triggering render method.

Upvotes: 0

Views: 2121

Answers (3)

Loamhoof
Loamhoof

Reputation: 8293

So as you requested, here's an example of how to override the trigger method. Note that you'll have to override it for all types of classes (Model, View, Collection, Router).

var trigger = Backbone.Model.prototype.trigger;
Backbone.Model.prototype.trigger = Backbone.View.prototype.trigger = Backbone.Collection.prototype.trigger = Backbone.Router.prototype.trigger = function(name) {
  trigger.apply(this, arguments);
  console.log(this, 'triggered the event', name, '.').
}

You could be more specific by overriding each method individually to add the type of object in the log. But you got the general idea.

Upvotes: 1

Cory Danielson
Cory Danielson

Reputation: 14501

The way that I always debug events is:

view.on('all', function(eventName){
    console.log('Name of View: ' + eventName);
});

You could do this on views, models or collections.

example: http://jsfiddle.net/CoryDanielson/phw4t/6/

I added the request and sync methods manually to simulate how backbone would actually perform. The rendered event is custom -- nothing listens to it. Just to show you how/when it happens.

Upvotes: 1

Acorn
Acorn

Reputation: 50497

You might what to give backbone.debug a try. Should give you some insight into what events are being fired.

Upvotes: 0

Related Questions