2

I'm just starting out with backbone / grails and i've been struggling to figure out how to get everything to work.

I'm building a pricing configurator where a user selects a product type from radio group A and radio group B containing the quantity / pricing / discount data will do an ajax call to the backend for updated pricing data. I do not want to expose my pricing algorithm to the front end, so I was thinking I would use backbone to handle my ajax request / template.

I do not want to fully rely on js to create my UI, so on the initial page load, I'll build the gsp view with grails. Only problem I've noticed was my gsp view was being replaced by my handlebars template on initial page load. I guess this is fine, except it does two identical queries which isn't optimal.

Anyhow my code that does not seem to be working.

<script id="priceTemplate" type="text/x-handlebars-template">
    <tr>
        <td><input type="radio" value="" name="quantity">{{quantity}}</td>
         <td class="price"><span>{{price}}</span></td>
        <td class="discount"><span>{{discount}}</span></td>
    </tr>
</script>

<asset:javascript src="bb_product/config.js"/>

<script>   
    var prices = new models.PriceList([],{productId:${productInstance.id}});
    var priceView = new PriceView({collection: prices});
    prices.fetch();     
</script>

Models

var models = {};

models.PriceModel = Backbone.Model.extend({   
    //Is the model automatically populated from the collections json response?
})

models.PriceList = Backbone.Collection.extend({
    initialize: function(models, options) {     
        this.productId = options.productId;
    },
    model: models.PriceModel,
    url: function() {
           return '../product/pricing/' + this.productId + '.json'
        }  
});

View

var PriceView = Backbone.View.extend({
    el: '#product-quantities',

    template: Handlebars.compile($("#priceTemplate").html()),

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

   render: function() {
       console.log('collection ' + this.collection.toJSON()) //comes back empty
       this.$el.html( this.template(this.collection.toJSON()));
   }

});

json returned from url

[{"id":1,"quantity":10,"price":"10","discount":"10"},{"id":2,"quantity":50,"price":"20","discount"
:"10"}]

To initially get this up and working, what am I missing to display all items in the json object?

I've also see this code around, not sure what it does this.listenTo(this.collection, 'reset', this.render);

1 Answer 1

2

The reason you don't see any items is that the items aren't actually in the collection until after the view is rendered. Look at these two lines of code:

var priceView = new PriceView({collection: prices});
prices.fetch();

The first line renders the view (since you're calling render from within initialize). However, at that time, the prices collection is empty. Then, the second line fetches the data from the server and loads it into the collection; but by that time, the view has been rendered.

That last line of code you posted is the key to fixing this:

this.listenTo(this.collection, 'reset', this.render);

Usually, you'll put this inside the initialize function in your view class. What this does is "listen" to the collection instance, and when the reset event occurs, it will call the this.render function. (Of course, the method this.listenTo can "listen" to other objects for other events; see more details in the Backbone documentation).

If you add that line to the view's initialize function, the view will re-render whenever a "reset" event happens on the collection.

HOWEVER, by default, the "reset" event happens when all the models in the collection are replaced with another set of models, and this doesn't happen by default when you call a collection's fetch method (instead, the collection will try to "smart-update"). To force a reset of the collection when using fetch, pass {reset: true} as a parameter:

prices.fetch({reset: true});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.