我正在尝试学习backbone.js,我无法理解如何绑定模型并在获取后读取它们.
这是我的代码:
这是我的代码:
$(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); }
这就是webservice json的样子
{ "AuctionState":3,"ClosedOn":null,"Bids":[ { "BidId":132,"AuctionId":26 },{ "BidId":131,"AuctionId":2 } ] }
我如何将该响应绑定到模型?
解决方法
您需要覆盖BidCollection上的parse()方法以将Bids拉出并将它们(仅限它们)呈现给集合的add()例程.您可以使用parse()方法执行其他操作来管理AuctionState字段.
您还需要在视图中侦听“更改”事件,以便在获取后视图自动更新.您不需要在视图中调用render();你应该将模型的’change’事件绑定到render(),然后获取数据并让它触发渲染.
与往常一样,Backbone的源代码具有高可读性.我建议学习和理解它.
例如:
var BidsList = Backbone.Collection.extend({ model: Bid,parse: function(response){ return response.Bids; } });