Carlos Azaustre
Carlos Azaustre

Reputation: 400

Backbone.js render a view with a collection

I'm n00b with Backbone/Require JS and I'm trying to run a View based in a Collection. I've split the code in files following MVC pattern This is my code for the view:

File: views/petDirectory

define([
  'jquery',
  'backbone',
  'models/pet',
  'collections/pets',
  'text!templates/pet/directory.html'
], function($, Backbone, PetModel, PetsCollection, petDirectoryTemplate){

var PetDirectoryView = Backbone.View.extend({

    el: $("#main"),
    template: _.template(petDirectoryTemplate),
    collection: new PetsCollection(),

    initialize: function() {
        var view = this;
        view.render();
    },

    render: function(){
        var view = this;
        var compiledTemplate = this.template({pets: view.collection});
        view.$el.html( compiledTemplate );
        return this;
    },
});

return PetDirectoryView;
});

Data is loaded via API RESTful in the models, and I create the instance of PetDirectoryView in router.js.

But I'm having something wrong (maybe asynchronus calls) because my template doesn't show the items and my Chrome Console shows something like this:

r {length: 0, models: Array[0], _byId: Object, constructor: function, url: "http://localhost:3000/pets"…}

Any ideas? Thanks in advance!

Upvotes: 0

Views: 1590

Answers (1)

Carlos Azaustre
Carlos Azaustre

Reputation: 400

While I'm writing the question I've the answer! Thanks StackOverflow! :D

The point is don't render the view before ends the callback function in fetch(). The code is above:

initialize: function() {
        var view = this;
        view.collection = new PetsCollection();
        view.collection.fetch({
            success: function(){
                view.render();
            }
        });
        console.log(view.collection);
        view.render();
},
render: function() { ... }

Upvotes: 2

Related Questions