我计划对单个模型及其集合进行单独的提取,但希望该集合遵循相同的模型结构。
目前,我每个都有单独的网址,但是它在jQuery错误Uncaught TypeError: Cannot read property 'length' of undefined
上崩溃了
我应该以不同的方式做这件事吗?代码如下:
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;
});
答案 0 :(得分:2)
是的,对于您的模型,您可以使用:
var Model = Backbone.Model.extend({
idAttribute: "Id",
urlRoot: function() {
return baseAPIUrl + '/CoreService/GetArticle';
}
});
然后,您将实例化您的模型,如下所示:
var model = new Model({Id: 2});
model.fetch();
您的api将调用以下网址,然后'host / CoreService / GetArticle / 2'
答案 1 :(得分:1)
是。您可以使用不同的模型和网址。集合。唯一要担心的是“url”和“urlRoot”。
对于模型,它将是:
var User = Backbone.Model.extend({
urlRoot:'/saveuser.php'
});
对于一个集合,它将是:
var Users = Backbone.Collection.extend({
url:'/saveuser.php'
});
干杯