我正在为自己构建一个测试应用程序,以了解有关 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 确实有效。但我希望该功能由集合上的“添加”事件触发。
我还尝试通过在创建新数据模型的循环中添加 @collection.trigger "add" 来手动触发事件。但这也不起作用。
任何想法我正在监督或做错了什么?