Kamil Davudov
Kamil Davudov

Reputation: 363

Converting Backbone model to JSON set default values

This is my Backbone model code where I set the default values.

App.Models.Stock = Backbone.Model.extend({
    defaults: {
        name:       '',
        quantity:   0,
        booked:     0,
        minimum:    0,
        active:     1
    },
    urlRoot: '/stock/'
});

And this is my Backbone view code where I'm waiting for button clicks.

templateItem: _.template($('#stockItem').html()),
events: {
    'click #openStock': 'showStock'
},
showStock: function(e) {
    var stock = new App.Models.Stock({
        id: $(e.currentTarget).data('id')
    });
    stock.fetch();
    $('#sidebar').empty().append(
        this.templateItem(stock.toJSON())
    );
}

The problem is that when we fetch the model the server returns the proper result, but when I try to convert it to JSON, Backbone set default values for the model! Why does it happen? What's wrong with my code?

Upvotes: 1

Views: 947

Answers (1)

Michael.Lumley
Michael.Lumley

Reputation: 2385

You need to put your stock.toJSON() into a callback of fetch. Fetch is asynchronous, so the values from your server are not loaded until after you call stock.toJSON(). At that point, the defaults are still set on stock rather than the values you loaded from the server.

Try...

stock.fetch({
    success: function() {
        $('#sidebar').empty().append(
            this.templateItem(stock.toJSON())
        );
    }
});

Upvotes: 2

Related Questions