I'm doing this inside one of my Views:
render: function($options) {
...
this.collection.on('reset', _(function() {
this.render($options);
}).bind(this));
....
}
The problem is, whenever reset
as well as the re-rendering has been triggered, a new reset
binding will be created, resulting 2x, 4x, 8x, etc. times of re-rendering as it goes on.
It's a bit tricky to move the binding into the initialize section (which should solve this issue), however since it's not an option, is there any other solution available, like having Backbone checking if this event has been bound before, or something?
I recently accomplished this using a javascript variable.
Outside of any functions, I declared:
Then, inside the function:
This worked for me pretty well.
Sure..
Backbone doesn't expose most of the API required to make it useful. That's alright, use it anyway.
First, define your event handler function as a named function
Then, defensively unbind the function each time render is called
Moving your binding to
initialize
would be best but assuming that you have good reasons not to, you could just set a flag:There are lots of different ways to implement the flag,
_.once
just nicely hides the flag checking. You could also trigger an event inrender
have a listener that unbinds itself:That's the same logic really, just dressed up in different clothes. You could also use an explicit flag and an
if
inrender
or assign a function tothis._finish
ininitialize
and that function woulddelete this._finish
.