I'm trying to learn Backbone to make a simple webapp. I'm a little confused on how models and collections interact.
I have a view where I would like to show a list of accounts owned by the user. I managed to get this working correctly by creating an AccountCollection and creating the parse function. However, if I set the parse/url properties inside the Account model, it stops working. If these properties are set, then the fetch() function in the AccountCollection will return results with no data. So my question is how changing the parse/url functions in the model affects the fetch() call made in the collection?
This is the view I'm using to render the accounts. I create an accountCollection, fetch the results from the server, and then render those results:
return Backbone.View.extend({
el: "#sidebar",
template: Handlebars.compile(viewTemplate),
initialize: function() {
var self = this;
self.accounts = new accountCollection();
//Here I fetch accounts from the server and list them
self.accounts.fetch().then(function(){
self.render();
});
},
render: function() {
//If I set url/parse in the account.js model, this.accounts data is wrong
var rendered = this.template({
accounts: this.accounts.toJSON()
});
$(this.el).html(rendered);
}
});
And then here is the code for the AccountCollection:
return Backbone.Collection.extend({
url: API+"accounts",
model: Account,
parse: function(data){
if(!data.success) {
return null;
} else {
return data.message;
}
}
});
And here is the Account model. Un-commenting these lines is what causes my problem:
return Backbone.Model.extend({
//THESE ARE THE LINES CAUSING MY PROBLEMS
// url: function(){
// return API+"accounts/"+this.id;
// },
// parse: function(data){
// if(!data.success) {
// return null;
// } else {
// return data.message;
// }
// },
defaults: {
name: null,
current_balance: 0
}
});
Why does changing the url and parse function in the model change the results returned by the collection's fetch() function? Does the collection somehow inherit from the model's parse function? If anybody can clear this up I would really appreciate it.
Aucun commentaire:
Enregistrer un commentaire