Apoorv Parijat
Apoorv Parijat

Reputation: 871

Why is Collection.fetch() not updating the view?

I've the following views for Rails TodoList app. There is no javascript error. I can even see the GET request for /todos by the .fetch() method. The problem is, there is no call to addOne function and hence no view update.

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

Also, I tried calling it manually using

this.addOne({task: "blah", done:"true"});

in the initialize function. This throws javascript error saying toJSON function is undefined.

Upvotes: 0

Views: 271

Answers (1)

Nicolas D.
Nicolas D.

Reputation: 26

I think you made a typo and wrote refresh instead of reset. The event is reset, so you have to replace this line:

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

with:

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

Upvotes: 1

Related Questions