Reputation: 35
Im using backbone, require.js and coffeescript in a application. Programming my app, discovered i have a problem with the views. Sorry for my english ! =)
My dom is :
<div id="header"></div>
<div id="container"></div>
Part of my app :
class AppRouter extends Backbone.Router
routes:
'': 'home'
'u/:user': 'user'
'events: 'events'
'messages': 'messages'
events: () ->
events = new EventsView
events.events()
messages: () ->
messages = new MessagesView
messages.messages()
class MessagesView extends Backbone.View
template: window.Handlebars.compile MessagesTpl
el : '#container'
events :
'click #test' : 'test'
test: () ->
console.log 'test'
messages: () ->
#fecth and bind render method on 'all'
class EventsView extends Backbone.View
template: window.Handlebars.compile EventsTpl
el : '#container'
events: () ->
#fetch and bind render method on 'all'
I have the following problem :
When I instance and call in the router ("messages") the messagesView, i do a fetch and the render works fine. Then when the router navigate to the other route ("events") and call eventsView, same thing happens, it renders the view correctly.
But if navigate again on the route "messages" the event "test" is fired two times ! , once for each instance !
I discovered if i call on the router $("#container").unbind() previous instance MessagesView , this fix the problem, but i dont know if my solution its really good.
My fear is that the DOM is being created evil and have high load. You know you can do with this?
Very thanks for all ! grettings from Argentina !
Alejandro
Upvotes: 0
Views: 530
Reputation: 7113
Your solution is fine, you're just unbinding and rebinding the events, should not be a problem. Because you use the same dom element, you have to render the view again, but normally that is not too heavy. I've used the same solution.
Alternatively, you could have separate dom elements for MessagesView and EventsView, create the views the first time the user goes to the route. Then you always hide and show the dom elements depending on the current route.
Upvotes: 1