Backbone.js bind collection to models after retrieval using ajax

I am trying to learn backbone.js and I am having trouble understanding how to bind models and read them after retrieval. This is my code:

$(function() { var Bid = Backbone.Model.extend(); var BidsList = Backbone.Collection.extend({ model: Bid, url: '/buyers/auction/latestBids?auctionId=26&latestBidId=0', }); var BidsView = Backbone.View.extend({ el: $('#bids'), initialize: function() { log('hi'); _.bindAll(this, 'render'); this.collection = new BidsList(); this.collection.fetch(); this.render(); }, render: function() { log(this.collection); return this; }, }); var bidsView = new BidsView(); }); function log(m) { console.log(m); } 

Here's what webservice json looks like

 { "AuctionState":3, "ClosedOn":null, "Bids":[ { "BidId":132, "AuctionId":26 }, { "BidId":131, "AuctionId":2 } ] } 

How do I bind this answer to a model?

+6
source share
1 answer

You need to redefine the parse () method on your BidCollection in order to pull out bids and submit them, and them only, to the add () collection procedure. You can do other things with the parse () method to control the AuctionState field.

You also need to listen for β€œchange” events in your view, so the view is automatically updated after retrieval. You do not need to call render () in your view; you must bind the model's change event to render (), then retrieve the data and let it trigger a render.

As always, the underlying source code is highly readable. I recommend learning and understanding it.

For instance:

 var BidsList = Backbone.Collection.extend({ model: Bid, url: '/buyers/auction/latestBids?auctionId=26&latestBidId=0', parse: function(response){ return response.Bids; } }); 
+9
source

Source: https://habr.com/ru/post/891135/


All Articles