Search code examples
javascriptjquerybackbone.js

Unable to display Todo Collection on the page


Iam practising Backbone JS, below is the code Iam tying to display Todo Collection on the page. But iam not understanding what went wrong with the below code and at end displaying nothing. BTW, Iam able to get data from server and console logs too showing correct data, but just not displaying on the page. Seems like my render calling before than getting data from server, but dont know why is that happening like that.

Here is the code, please suggest me what went wrong?

<html>
<head>
<link rel="stylesheet"
    href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
</head>

<body>

<div id="demo"></div>

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>

<script type="text/javascript">

var TodoItem = Backbone.Model.extend({
    urlRoot: 'api',
})

var TodoCollection = Backbone.Collection.extend({
    model: TodoItem,
    url: 'api/todos'
})

var TodoView = Backbone.View.extend({
    template: _.template('<h3> ' +'<input type=checkbox ' +'<% if(status === "complete") print("checked") %>/>' +' <%= description %></h3>'),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }

})

var TodoListView = Backbone.View.extend({
    initialize: function(){
        this.listenTo(this.collection,'reset',this.render);
        this.collection.fetch({reset:true});
    },
    render: function(){
        console.log(this.collection.length);
        this.collection.forEach(this.addOne,this);
    },
    addOne: function(todoItem){
        console.log(todoItem.get('description'));
        var todoView = new TodoView({model: todoItem});
        this.$el.append(todoView.render());
    }

});


var todoItem = new TodoItem()
var todoList = new TodoCollection()

var todoListView = new TodoListView({el: '#demo', collection: todoList})

</script>

</body>

</html>

Solution

  • The problem is you are appending this which is returned from the view.You have to attach el of view to DOM.

    this.$el.append(todoView.render().el);