0

I am using backbone-relational. The usage for a onetomany model works fine.

But I am having troubles using backbone-relational for a single/standalone model:

window.BeerOnlineShopPosition = Backbone.RelationalModel.extend({
urlRoot:"../api/beeronlineshoppositions",
idAttribute: 'id',
relations: [                
],
defaults:{
    "id":null,
    "position_amount":""
}
});

window.BeerOnlineShopPositionCollection = Backbone.Collection.extend({
model:BeerOnlineShopPosition,
url:"../api/beeronlineshoppositions"
});

in main i have:

    beeronlineshopproductDetails:function (id) {
    var beeronlineshopproduct = BeerOnlineShopProduct.findOrCreate(id);
    beeronlineshopproduct.fetch();

   var beeronlineshopproduct_view = new BeerOnlineShopProductView({el: $('#content'), model: beeronlineshopproduct});

},

So, when jump to an existing records (...beeronlineshop/beeronlineshopproducts/#4), nothing happens. But debugging shows, that the fetch is executed and the view gets loaded. but the view is not rendered somehow.

When I refresh (f5), the view gets rendered correctly.

As mentioned the whole thing works for one-to-many model, so my question is:

did i make some trivial syntax-error on the model part?... or is there any other obvious reason for the troubles i have?

Amrit
  • 2,295
  • 4
  • 25
  • 42
engulfing
  • 11
  • 3
  • maybe backbone-relational supports only models with nesting. using backbone.js seems to do the job. but without "findOrCreate" of course. if anyone could verify would be great. – engulfing Jul 22 '13 at 09:13

1 Answers1

0

It may be because of the asynchronous request created by findOrCreate. beeronlineshopproduct.fetch() is making a request to the server but the view is being rendered before the server returns with a response.

You have two options. You can pass in the rendering of the view as a callback upon fetch's success like so:

beeronlineshop.fetch({
  success: function() {
    var beeronlineshopproduct_view = new BeerOnlineShopProductView({el: $('#content'), model: beeronlineshopproduct})
  });

Or you can pass an initializer in your BeerOnlineShopProductView that listens to the its model syncing with the server, and calls for the view to re-render itself, like so:

window.BeerOnlineShopProductView = Backbone.View.extend({
  initialize: function() {
    this.listenTo (this.model, "sync", this.render)
  },
})    
Ricky Zein
  • 557
  • 1
  • 4
  • 8