2013-08-23 35 views
1

我正在爲自己構建一個測試應用程序,以瞭解更多關於coffeescript,Backbone,Brunch.io和Chaplin JS的信息,但我卡住了我無法弄清楚我做錯了什麼。卓別林/ Backbone問題 - 添加項目到集合時未添加事件「添加」事件

這是我在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」手動觸發事件。但是這也沒有奏效。

任何想法我監督或做錯了什麼?

+0

To TodoView。該集合也綁定到TodoView。 – Stefan

回答

1

斯特凡,

我有類似的問題時,我試圖用事件監聽哈希值。我選擇在視圖的初始化方法中設置偵聽器。

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

-Hans

+0

很久以前我有這個問題。憑藉我目前的知識,我可以確認這是解決方案。謝謝! – Stefan

0

@stefan和@hans, 這解決您的問題毫無疑問的,但你們是不是利用權力的chaplin收集視圖。它默認處理對集合的任何修改。如果你添加/刪除/改變一個新模型,它會重新渲染自己,不需要強制。 找到的卓別林doc here