Chaplin / Backbone问题 - 在向集合添加项目时未触发“添加”事件

时间:2013-08-23 19:09:27

标签: javascript events backbone.js coffeescript chaplinjs

我正在为自己构建一个测试应用程序,以了解有关coffeescript,Backbone,Brunch.io和Chaplin JS的更多信息,但我陷入了困境,我无法弄清楚我做错了什么。

这是我在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 })

问题是:未触发事件侦听器(在侦听器对象中设置)。所以不调用@renderTodoList。

直接从@initialize函数调用@renderTodoList确实有效。但我希望函数由集合上的“add”事件触发。

我还尝试通过在创建新数据模型的循环中添加@ collection.trigger“add”来手动触发事件。但这也不起作用。

我在监督或做错了什么想法?

2 个答案:

答案 0 :(得分:1)

的Stefan,

当我尝试将listen hash用于事件时,我遇到了类似的问题。我选择在视图的initialize方法中设置监听器。

@listenTo @Collection,'添加',@ renderTodoList,@

-Hans

答案 1 :(得分:1)

@stefan和@hans, 毫无疑问,这解决了你的问题,但你们没有利用chaplin集合视图的强大功能。它默认处理对集合的任何修改。如果你添加/删除/更改一个新模型,它会重新渲染自己,不需要强制。 找到卓别林 doc here