Question

I have a container .js-todoslist for todo lists. Also I have several views TodosListView for each todolist. All TodosListView's are created from parent view and binded to the same el .js-todoslist.

Todos lists are not rendered on initialize, I need to render different Todos' lists by clicking buttons so each list has showTodolist method that shows it.

The problem is, though at the moment only one list can be rendered, all of them are actually initialized. And when I press .add-btn in rendered List, all lists have add function trigged (not only current rendered).

TodosListView = Backbone.View.extend
  events:
    "click .add-btn": "add"

  initialize: (options) ->
    self = this
    @model = @options.model

    # I've tried to undelegate event after initialize, but no luck
    # @$el.undelegate('.add-btn', 'click');
    # @undelegateEvents()

  # show this todolist
  showTodolist: ->
    @$el.html @template(@model.toJSON())

  render: ->
    @

  add: ->
    console.log "Add to Todos list #" + @model.get("id")

How to avoid this (excpt creating different views for each list)? Thanks.

Was it helpful?

Solution

Your problem is that since you are using the same el for different views, when you render a view it does not unbind the events of the previous view.

Before rendering the view, use:

this.undelegateEvents();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top