Ryan Bobrowski
Ryan Bobrowski

Reputation: 2730

Backbone multiple views on one element

I'm having an issue with view events being applied multiple times on the same view. I know this is because I am binding multiple views to the same el - so when I load one view, go to another, and then come back to the first one, it's applying the events again on top of the existing ghosted ones, since it's creating a new WhateverView() from the router each time.

According to this question I need to call view.model.off( null, null, this ); to reset the events. Unfortunately...I'm not using models for any of my views. Maybe this is completely the wrong way to go about things, but right now my views are essentially just different static pages in an SPA. I will have actual data eventually and I'll be using models/collections, but for now I just want different static pages in my app to be rendered in some container. I'm using requirejs and the text plugin and it works great so far...except for this event thing.

I've also tried calling this.undelegateEvents(); before I render each view (in case the view in question had already been rendered at least once before) but it doesn't seem to do anything.

Upvotes: 3

Views: 558

Answers (1)

Oakley
Oakley

Reputation: 666

It sounds like you are attaching event listeners to elements each time you create the view. I was able to resolve this problem in an app by doing the following:

$( '#coolbutton').off('click').on('click', coolFunc);

Using the events object, calling:

this.undelegateEvents();
this.$el.removeData().unbind();

when removing the view works as well.

Upvotes: 1

Related Questions