javascript - Chaplin/Backbone 问题 - 将项目添加到集合时未触发 "Add"事件

标签 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 确实有效。但我希望该函数由集合上的“添加”事件触发。

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

有什么想法是我监督的或做错了什么吗?

最佳答案

斯特凡,

当我尝试对事件使用监听哈希时,我遇到了类似的问题。我选择在 View 的初始化方法中设置监听器。

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

-汉斯

关于javascript - Chaplin/Backbone 问题 - 将项目添加到集合时未触发 "Add"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18410182/

相关文章:

javascript - 如何查找 context.fillText(text, x, y) 的尺寸

php - $(document).ready() 什么时候触发?

javascript - 如何让 Backbone.ajax 成功返回数据

javascript - 如果我使用 _.bindAll(this) 为什么我的 Backbone.View.constructor.__super__ 未定义

javascript - Node Passport-azure-ad 错误 : "unknown authentication strategy "oauth-bearer""

javascript - 一种在 iOS (iPhone, iPad) 上跳过崩溃的方法

objective-c - NSTextField 没有诸如 'Editing did Change' 之类的事件?

javascript - 如何将 Backbonejs 路由器与 Twitter Bootstrap 选项卡结合起来?

javascript - 禁用缩放 chrome 技巧

javascript - 如何获取 Google 可视化表以对存在的格式化单元格值进行排序?