为什么Collection.fetch()没有更新视图?

时间:2012-06-21 11:29:58

标签: javascript ruby-on-rails backbone.js

我对Rails TodoList应用程序有以下视图。没有javascript错误。我甚至可以通过.fetch()方法看到/ todos的GET请求。问题是,没有调用addOne函数,因此没有查看更新。

$(function(){
Todos = new TodoList.Collections.Todos;
TodoList.Views.TodoView = Backbone.View.extend({
    tagName: "li",
    events: {},
    initialize: function(){},
    template: _.template('<li> {{task }}</li>'),
    render: function(){
        var todo = this.model.toJSON();
        //return this.template(todo);
        return "blah";
    }
});

TodoView = TodoList.Views.TodoView;

TodoList.Views.AppView = Backbone.View.extend({
    el: $("#todo_app"),
    events: {
        "submit form#new_todo": "createTodo"
    },
    initialize: function(){
        _.bindAll(this, 'addOne', 'addAll','render');
        Todos.bind("add", this.addOne);
        Todos.bind("refresh", this.addAll);
        Todos.bind("all", this.render);
        Todos.fetch();
    },

    addOne: function(todo){
        var view = new TodoView({model: todo});
        this.$("#todo_list").append(view.render().el);
        alert("here");
    },

    addAll: function(){
        Todos.each(this.addone);
    },

    newAttributes: function(event){
        var new_todo_form = $(event.currentTarget).serializeObject();
        return {
            dog: {
                name: new_todo_form["todo[task]"],
                age: new_todo_form["todo[done]"]
            }
        };
    },

    createTodo: function (e){
        e.preventDefault();
        var params = this.newAttributes(e);
        Dogs.create(params);
    }
});
});

另外,我尝试使用

手动调用它
this.addOne({task: "blah", done:"true"});
初始化函数中的

。这会引发javascript错误,说toJSON函数未定义。

1 个答案:

答案 0 :(得分:1)

我认为您写了一个拼写错误并写了refresh而不是reset。事件为reset,因此您必须替换此行:

Todos.bind("refresh", this.addAll);

使用:

Todos.bind("reset", this.addAll);
相关问题