Search code examples
javascripteventsbackbone.jscoffeescriptchaplinjs

Chaplin/Backbone issue - "Add" event not fired when adding item to the collection


I'm building a test application for myself, to learn more about coffeescript, Backbone, Brunch.io and Chaplin JS, but I'm stuck and I can't figure out what I'm doing wrong.

This is my code in the todo-view.coffee:

View = require 'views/base/view'
TodoItemView = require 'views/todo/todo-item'
TodoItemModel =  require 'models/todo/todo-item-model'
TodoItemCollection = require 'models/todo/todo-collection'

# Site view is a top-level view which is bound to body.
module.exports = class TodoView extends View

  # Template data stuff
  container: 'todo-container'
  tagName: 'ul'
  className: 'todo-list'
  template: require './templates/todo'

  # Create a custom initialize method
  initialize: ->
    super

    # Create a new Backbone Collection with some dummy data to store
    @collection = new TodoItemCollection() 

    # Store the dummy data in the collection
    data = ["working", "studying", "gym", "sleep"]
    for todoItem in data 
      @collection.add( new TodoItemModel({ item: todoItem }) )

    # Render the view
    @render()

  # Listen to data events
  listen: 
    "add collection": "renderTodoList"

  # When the template is initialized we need to load
  # all the list items and append them to the container
  renderTodoList: ->

    # Loop over all the items
    for model in @collection.models
      todoItemView = new TodoItemView({ container: @$el, model: model })

The problem is: the event listener ( set in the listener object ) isn't triggered. So the @renderTodoList isn't called.

Calling the @renderTodoList directly from the @initialize function does work though. But I want the function to be triggered by the "add" event on the collection.

I've also tried to trigger the event manually by adding @collection.trigger "add" in the loop that creates the new data models. But this didn't work neither.

Any ideas what I'm overseeing or doing wrong?


Solution

  • Stefan,

    I had similar issues when I tried to use the listen hash for events. I opted to setup the listener as such in the initialize method of the view.

    @listenTo @Collection, 'add', @renderTodoList, @

    -Hans