【问题标题】:Why is Collection.fetch() not updating the view?为什么 Collection.fetch() 不更新视图?
【发布时间】:2012-06-21 11:29:58
【问题描述】:

我对 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 函数未定义。

【问题讨论】:

  • 我认为该事件已重命名为 reset。所以试试这个Todos.bind("reset", this.addAll);

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


【解决方案1】:

我认为你打错了字,写了refresh 而不是reset。事件是reset,所以你必须替换这一行:

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

与:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多