Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 563
Ryan Bobrowski Avatar asked Feb 04 '26 23:02

Ryan Bobrowski


1 Answers

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.

like image 54
Oakley Avatar answered Feb 06 '26 15:02

Oakley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!