簡體   English   中英

Backbone.js不使用.each()遍歷集合

[英]Backbone.js Not Iterating Over Collection Using .each()

我一直在做一些Backbone.js編碼,遇到了一個特殊的問題,在該問題上我無法遍歷集合的內容。 Tasker_TodoList.each(this.addOne, this); 由於某種原因, AppViewaddAll函數中的AppView未正確執行,拋出錯誤: Uncaught TypeError: undefined is not a function

鏈接: 運行應用程序時出現錯誤 ->在輸入框中輸入內容,然后按“ +”按鈕在控制台中看到錯誤。

有問題的代碼是:

$(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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM