cpeele00
cpeele00

Reputation: 893

backbone.js example doesn't run upon page load but does when invoked in debugger

I have a simple backbone.js example I am working on. The problem is upon page load it is not displaying anything on the page. However, in the Chrome debugger console, if I explicitly make a call to the view and it's render() method then the results show up on the screen with the correct json data.

Any help would be really, really appreciated!

var Clients = Backbone.Collection.extend({

    model: Client,
    url: 'api/Contacts'

});

var clients = new Clients();


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


var UserListView = Backbone.View.extend({
    el: $('#contacts'),

    render: function() {
        this.$el.empty();
        var self = this;

        _.each(this.collection.models, function(model) {
            self.renderItem(model);
        });
    },

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

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

Here's the code for the index.html page:

<ul id="contacts"></ul>

<script id="contacts-template" type="text/template">

    <%= FirstName %> <%= LastName %>

</script>


<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script src="scripts/app/app.js"></script>
<script>

    $(document).ready(function () {

        alert('HI'); // I verified this alert works

        clients.fetch();

        var userListView = new UserListView({ collection: clients });

        userListView.render();

    });

</script>

Upvotes: 1

Views: 744

Answers (1)

Isaac Zepeda
Isaac Zepeda

Reputation: 310

Every asynchronous call should have a callback when it's done, here you're trying to use clients collection before it has data from the server. I would change the code to:

$(document).ready(function () {
    alert('HI'); // I verified this alert works
    clients.fetch(
        success: function() {
            var userListView = new UserListView({ collection: clients });
            userListView.render();
        },

        error: function() {
            alert('An error has occurred');
        },
    );
});

Regards,

Upvotes: 2

Related Questions