Reputation: 1450
I plan on doing separate fetches for an individual model and its collection, but would like the collection to follow the same structure of the model.
Currently, I have separate urls for each, but its crashing on a jQuery error Uncaught TypeError: Cannot read property 'length' of undefined
Should I be doing this a different way? Code is below:
ArticleModel.js
define([
'underscore',
'backbone',
], function(_, Backbone) {
var ArticleModel = Backbone.Model.extend({
defaults: {},
url : function() {
return baseAPIUrl + '/CoreService/GetArticle';
},
parse : function(data) {
console.log(data);
var articleArray = [];
$.each(data.Articles, function(i, item) {
if (isNotEmpty(item.ScaledImages)) {
var Image = item.ScaledImages.ImageUrls[4].Value;
}
articleArray = {
Id : item.Id,
Title : item.Title,
FeedTitle : item.FeedTitle,
Summary : item.Summary,
ImageUrl : Image,
Link: item.Link
};
});
return articleArray;
}
});
return ArticleModel;
});
ArticlesCollection.js
define([
'underscore',
'backbone',
'models/article/ArticleModel'
], function(_, Backbone, ArticleModel){
var ArticlesCollection = Backbone.Collection.extend({
model: ArticleModel,
initialize : function(articles, options) {
},
url : function() {
return baseAPIUrl + '/CoreService/GetFollowedMembersArticles';
},
parse : function(data) {
var articleArray = [];
$.each(data.Articles, function(i, item) {
if (item.ScaledImages != null) {
var image = item.ScaledImages.ImageUrls[4].Value;
}
articleArray.push({
Id : item.Id,
Title : item.Title,
FeedTitle : item.FeedTitle,
Summary : item.Summary,
ImageUrl : image,
Link: item.Link
});
});
return articleArray;
}
});
return ArticlesCollection;
});
Upvotes: 1
Views: 415
Reputation: 6938
Yes. You can have different urls for models & collections. Only thing to worry would be the "url" and "urlRoot".
For a model it would be :
var User = Backbone.Model.extend({
urlRoot:'/saveuser.php'
});
For a collection it would be :
var Users = Backbone.Collection.extend({
url:'/saveuser.php'
});
Cheers
Upvotes: 1
Reputation: 4244
Yes, for your model you would use:
var Model = Backbone.Model.extend({
idAttribute: "Id",
urlRoot: function() {
return baseAPIUrl + '/CoreService/GetArticle';
}
});
You would then instantiate your model like follows:
var model = new Model({Id: 2});
model.fetch();
Your api will call the following url then 'host/CoreService/GetArticle/2'
Upvotes: 2