我一直在做一些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();
});


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

最佳答案

从此更改AppView上的初始化函数:

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


对此:

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

10-06 01:32