Timothée HENRY
Timothée HENRY

Reputation: 14604

Backbone.js MVC way to render the view AFTER the data is received back from the server on a fetch?

I wish to read a whole database table to fill a Backbone.js Collection, before updating a View.

I am using fetch and listening to the reset event.

My problem is the reset event fires up before the http request is made to the server.

My question is: how can I render the view AFTER the data is received back from the server on a fetch?

Here is a jsfiddle showing the problem (with a debugger placed at reset):

http://jsfiddle.net/GhaPF/16/

The code:

$(document).ready(function() {

    var Item = Backbone.Model.extend({
        urlRoot : './items'
    });

    var ItemList = Backbone.Collection.extend({
        model: Item,
        url: './items/',
    });


    var ItemListView = Backbone.View.extend({
        el: 'body',
        initialize: function(myitemList) {
            this.itemlist = myitemList;
            this.itemlist.bind('reset', this.debuggThis());
        },
        debuggThis: function() {
            debugger;
        },
        render: function() {

        },
        events: {
            "keypress #new-item":  "createOnEnter"
        },
        createOnEnter: function(e) {
        }
    });

    $("#new-item").focus();
    var itemlist = new ItemList();
    var myitemListView = new ItemListView(itemlist);
    itemlist.fetch();
});​

The following code works, but it just doesn't feel like proper backbone.js (MVC) code since it would be placed outside of the View definition:

itemlist.fetch().complete(function(){

Upvotes: 0

Views: 258

Answers (2)

squaretone
squaretone

Reputation: 370

Maybe the issue is this line:

this.itemlist.bind('reset', this.debuggThis());

Should actually be:

this.itemlist.bind('reset', this.debuggThis);

Your debugThis function was getting run at the time you set up the listener for the 'reset' event - not when the event is triggered. This was telling JavaScript that you wanted debugThis to return a callback function instead of having debugThis "be" the callback function.

Also, orangewarp's comment about passing 'this' as the third parameter is probably relevant too. Sot it would end up as:

this.itemlist.bind('reset', this.debuggThis, this);

Upvotes: 3

jmk2142
jmk2142

Reputation: 8581

That's strange. When you fetch() the reset event should be triggered AFTER your collection is populated. So I'm thinking the phenomena that reset happens before the http request is fired up may not be what you think it is.

Instead of using the complete... you could always just use the success callback option like this:

itemlist.fetch({
    success: function() {
        // Whatever code you want to run.
        itemlist.debuggThis();
    }
});

Also, when binding your reset you probably want this:

this.itemlist.bind('reset', this.debuggThis, this);

Upvotes: 2

Related Questions