我制作了一个模型,我用它来显示一个乐队的整个唱片,我用API作为JSON提供。到目前为止一切都那么好,但我需要通过发布的方式对相册进行排序,所以我打算使用comparator
- 方法,这在模型上无法使用。所以我想把模型“转换”成一个集合,还是有更好的方法?
这是我在discography.js上定义的模型:
ArtistDiscography.ArtistDiscographyModel = Backbone.Model.extend({
url: function() {
return App.APIO + '/i/artist/' + this.get('slug') + '/releases';
},
parse: function(response){
return response.data;
},
});
slug
值是JSON值,返回例如rihanna
。 JSON文件还包含一个名为releaseDate
的值。
在我的maincontroller.js中,我有这个:
define(function (require, exports, module) {
var ArtistDiscographyModule = require('modules/discography');
)};
ArtistController.prototype.initDiscography = function(name) {
this.artistdiscographyModel = new ArtistDiscographyModule.ArtistDiscographyModel({slug: name});
this.artistdiscographyModel.fetch();
this.artistdiscographyModel.on('sync', function() {
this.artistDiscographyView = new ArtistDiscographyModule.View({model: this.artistdiscographyModel});
App.useLayout('artistDiscography', 'artistDiscography').setViews({
'.releasesDiv' : this.artistDiscographyView,
}).render();
}, this);
};
JSON响应是:
data: [{
"slug" : "rihanna",
"releases": {
"title" : "Music Of The Sun",
"releaseDate": "2005-08-29",
"tracks": [{ //array of tracks}]
}, {
"title" : "Pon de Replay",
"releaseDate": "2005-08-22"
"tracks" : [{ //array of tracks}]
}
}]
有人可以帮帮我吗?我真的很感激!
答案 0 :(得分:0)
您可以将集合设置为模型的属性:
ArtistDiscography.ArtistDiscographyModel = Backbone.Model.extend({
defaults: {
slug: '',
releases: new Releases()
}
});
Releases = Backbone.Collection.extend({
model: Release
});
Release = Backbone.Model.extend({
defaults: {
title: '',
releaseDate: '',
tracks: []
}
});
然后您可以将比较器添加到Releases
集合中。
或者你可以变脏并使用数组的underscore's sort函数:
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]
答案 1 :(得分:0)
你有没有试过这些方面的东西?....
ArtistDiscographyCollection = Backbone.Collection.extend({
model: ArtistDiscography.ArtistDiscographyModel,
comparator: function (model) {
return (model.get('releases').releaseDate);
}
});