Reputation: 419
I have a fiddle here
That contains a model
Item = Backbone.Model.extend({....})
Apvdtl = Backbone.Model.extend()
and a collection
Apvdtls = Backbone.Collection.extend({
model: Apvdtl
})
and populate the collection with Apvdtl Model e.g.
apvdtls.add([{ itemid: 'c4676cef679a11e28b7a3085a942bd8e', qty: 10 },
{ itemid: '1da17339690f11e285d63085a942bd8e', qty: 5 }])
and generated this view
but what im trying to do is to is to make a view like this
by fetching the Item with ID on this JSON File
ApvdtlView = Backbone.View.extend({
tagName: 'tr'
initialize: function(){
this.model.on('change', this.render, this);
this.template = _.template('<td><%=itemid%></td><td><%=qty%></td>');
},
render: function(){
item.set({'id': this.model.get('itemid')});
// item = {id: 'c4676cef679a11e28b7a3085a942bd8e'}
item.fetch(); // but this doesnt get the data
// this should contain this data after i fetch
// item = {"id": "c4676cef679a11e28b7a3085a942bd8e",
// "code": "prp125", "descriptor": "Paper", "price": "7.00"}
// build new data to render
var data = {
"itemid": item.get('descriptor'),
"qty": this.model.get('qty')
}
this.$el.html(this.template(data));
//this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
Upvotes: 1
Views: 267
Reputation: 55740
First Ajax is Async . So you never know when the response comes back, so it is better to attach it to an event.
ApvdtlView = Backbone.View.extend({
tagName: 'tr',
initialize: function () {
// This listens to the sync and change event and renders the item
this.listenTo(this.model, 'change sync', this.render);
this.template = _.template('<td> <%=itemid%> </td>' +
'<td><%=qty%></td>');
this.model.fetch();
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
Next url
property has to be set for the Model ApvdtlView
as that is being fetched from the server.
Next is you cannot hit this url from your domain
urlRoot: 'https://raw.github.com/jrsalunga/prism2/master/www/api/item.json'
as it is a different domain as it violates the cross origin policy. You need to use jsonp
to get this
Now you can see the data that is fetched in the network tab but throws an error since the callback has to be handled serverside
Upvotes: 1