不能从Backbone.View的方法调用Backbone.collection的方法与require.js

时间:2012-08-19 17:58:19

标签: javascript backbone.js

我想从AppView调用collection的方法。但它不能。我的代码是这样的。

todolist.js

define(["todolist","todo"],function(TodoList,Todo){
    var TodoList = Backbone.Collection.extend({
            url: "/todos",
            initialize:function(){
                this.fetch();
                this.bind("add",this.update,this);
            },
            add:function(){
                console.log("added");
            },
            update:function(){
                    console.log("update!");

                    }
    });

    return TodoList;
});                                                                                                

app.js

 define(["jquery","underscore","backbone","todo","todolist","todo_view"],
    function($,_,Backbone,Todo,TodoList,TodoView){
        var AppView = Backbone.View.extend({
                initialize:function(){
                    this.collection = new TodoList;
                    this.collection.update();
                },
                events:{
                    "keypress #new-todo":"create",
                },
                    create:function(e){
                        if (e.keyCode === 13){
                            var txt = $("#new-todo").val();
                            var todo = new Todo({title: txt});
                            this.collection.add(todo.toJSON());
                        }
                    }
                }
        );
        return new AppView({el: $("body")});
});

但我不知道为什么this.collection.update()方法输出undefined。你有什么主意吗? 我的所有代码都在https://github.com/haradashinya/my-todo-redis

提前致谢。

1 个答案:

答案 0 :(得分:1)

错误在于您的app.js定义。它应该返回AppView而不是它的实例,该实例应该在模块定义之外创建。就像现在一样,到它返回todolist时还没有定义。