Backbone.js不使用.each()迭代集合

时间:2012-10-14 15:51:47

标签: javascript jquery html backbone.js underscore.js

我一直在做一些Backbone.js编码,遇到了一个特殊的问题,我无法迭代集合的内容。 Tasker_TodoList.each(this.addOne, this);addAll函数中的AppView行由于某种原因未正确执行,引发错误:Uncaught TypeError: undefined is not a function

链接: RUNNING APP WITH ERROR - >在输入框中键入内容,按“+”按钮,在控制台中看到错误。

有问题的代码是:

$(function() {
    var Todo = Backbone.Model.extend({
    defaults: {
        title: "Some Title...",
        status: 0 //not completed
    }
    });

    var TodoList = Backbone.Collection.extend({
        model: Todo,
        localStorage: new Store('tasker')
    });

    var Tasker_TodoList = new TodoList();

    var TodoView = Backbone.View.extend({
        tagName: 'li',

        template: _.template($('#todoTemplate').html()),

        events: {
            'click .delbtn': 'delTodo'
        },

        initialize: function(){
            console.log("a new todo initialized");
            //this.model.on('change', this.render, this);
        },

        render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        delTodo: function(){
            console.log("deleted todo");
        }
    });

    var AppView = Backbone.View.extend({
        el: 'body',

        events: {
            'click #addBtn': 'createOnClick'
        },

        initialize: function(){
            Tasker_TodoList.fetch();
            Tasker_TodoList.on('add', this.addAll);
            console.log(Tasker_TodoList);
        },


        addAll: function(){
            $('#tasksList').html('');
            console.log("boooooooma");
            Tasker_TodoList.each(this.addOne, this);
        },

        addOne: function(todo){
            console.log(todo);
        },

        createOnClick: function(){
            Tasker_TodoList.create();
        }

    });

    var Tasker = new AppView();
});

有人可以帮助我找出我做错了什么吗?谢谢大家的帮助: - )

1 个答案:

答案 0 :(得分:1)

在AppView上更改初始化函数:

Tasker_TodoList.on('add', this.addAll);

到此:

Tasker_TodoList.on('add', this.addAll,this);