0

I'm trying to learn nested views with Backbone.js and have run into a problem. No errors are thrown however, it does not display any output or data. Any help would be much appreciated. V/R Chris

link to jsFiddle: http://jsfiddle.net/cpeele00/PcmMW/8/

var User = Backbone.Model.extend({});

var Users = Backbone.Collection.extend({
    model: User
});

var UserItemView = Backbone.View.extend({
    tagName: 'li',
    template: _.template($('#user-list-template').html()),
    render: function() {
        this.$el.html(this.model.toJSON());
        return this;
    }
});

var UserListView = Backbone.View.extend({

    render: function() {
        this.$el.empty();
        var self = this;
        this.collection.each(function(model) {
            self.renderItem(model);
        });
    },

    renderItem: function(item) {
        var itemView = new UserItemView({
            model: item
        });

        this.$el.append(itemView.render().el);
    }

});

var user1 = new User();
user1.set({
    firstname: 'momo',
    lastname: 'peele'
});

var user2 = new User();
user2.set({
    firstname: 'bobo',
    lastname: 'peele'
});

var users = new Users([user1, user2]);

var listView = new UserListView({
    collection: users
});
listView.render();

Here's the html and template markup

<div id="user-list">
  <fieldset>
    <legend>Users</legend>
    <ul></uL>
  </fieldset>
</div>

<script id="user-list-template" type="text/template">
    <%= firstname %> 
    <%= lastname %> 
</script>

1 Answer 1

3

There seem to be two problems:

First, typo in UserItemView: you're not using the template, just appending JSON. Instead of

this.$el.html(this.model.toJSON());`

it should be

this.$el.html(this.template(this.model.toJSON()));

Second, the UserListView isn't attached to the DOM anywhere, so when it gets "rendered", it doesn't appear. I added

el: $("#user-list ul") 

to the view, so that rendering appends the sub-view items to an element that's actually in the DOM.

Forked Fiddle

PS, Firebug is your friend.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! yeah, I use Chrome debugger for the apps I write but it didn't occur to me to actually use that with jsFiddle. Thanks again and take care!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.