Reputation: 23
My problem is in the parse function I think:
/*global define */
define([
'jquery',
'underscore',
'backbone',
'models/article'
], function ($, _, Backbone, Article) {
'use strict';
var Articles = Backbone.Collection.extend({
model: Article,
url: "http://127.0.0.1:3000/posts",
initialize: function() {
},
parse: function(response) {
return response;
}
});
return new Articles();
});
I got this error after the parse function is executed:
Uncaught TypeError: Cannot read property 'idAttribute' of undefined
for example when I set return response.somthing; instead of return response; there is no error message.
and here is the response object:
[
{
"name": "test",
"description": "test",
"price": 0,
"category": "test",
"id": 0
},
{
"name": "test",
"description": "test",
"price": 0,
"category": "test",
"id": 1
},
{
"name": "test",
"description": "test",
"price": 0,
"category": "test",
"id": 2
},
]
and here is my model declaration:
define([
'jquery',
'underscore',
'backbone'
], function ($, _, Backbone) {
'use strict';
var Article = Backbone.Model.extend({
defaults: {
name: '',
description: '',
price: 0,
category: ''
},
initialize: function() {
}
});
return new Article();
});
Upvotes: 2
Views: 987
Reputation: 10585
It would be helpful to see the client (where the sync
or fetch
actually resides, for instance) but I would venture the following:
The function parse
is taking as an argument response
and returning it.
response
is whatever the server is returning as JSON
.
A Backbone
model is more than just its JSON
representation; it is wrapping that JSON
and giving it more functionality (like the idAttribute
for instance).
So by returning response
you are just returning some array (based on your response
you posted).
Instead of using parse
, I would just let the default method do whatever it does, because it looks like your response
is already ready to be parsed.
What I would do is to first return the type instead of the instance from your define
d modules for Article
and Articles
:
In models/article.js
return Article; // not return new Article;
In your collection definition
return Articles; // not return new Articles;
Now, from your client:
var articlesCollection = new Articles();
You fetch the collection:
articlesCollection.fetch({
success: function(collection, response) {
// now collection is a reference to articlesCollection and it will have models in it collection.models
},
error: function(collection, response) {
}
When you do, you'll have by default the following sort of models:
collection.at(0)
Article
attributes: { all your properties from the JSON of each object }
Does this clarify things at all?
Upvotes: 1