我正在创建一个单页应用,允许用户根据两个条件(技能和位置)过滤数据。此数据将从两个单独的Web服务填充。
每个服务都有一个模型,可以使用REST样式请求来使用数据。
我想在这一个视图中使用两位数据。根据我的理解,集合可以容纳一种类型的模型的多个实例,例如“电影”
var Movies = Backbone.Collection.extend({
model: Movie,
initialize: function() {
console.log("");
console.log("Movie Collection initialize");
console.log(this);
console.log(this.length);
console.log(this.models);
}
});
var movie1 = new Movie({
"title": "Bag It",
"averageUserRating": 4.6,
"yearReleased": 2010,
"mpaaRating": "R"
});
var movie2 = new Movie({
"title": "Lost Boy: The Next Chapter",
"averageUserRating": 4.6,
"yearReleased": 2009,
"mpaaRating": "PG-13"
});
但是我正在尝试实现下面的模式,其中集合有两个模型。这是Backbone的反模式吗?该如何解决?
define([
'underscore',
'backbone',
'models/locationsModel',
'models/skillsModel'
], function (_, Backbone, Location, Skills)
{
'use strict';
var FiltersCollection = Backbone.Collection.extend({
// The filters collection requires these two models that will provide data to the filters view
location: new Location(),
skills: new Skills(),
initialize: function() {
//Do stuff
}
});
return new FiltersCollection();
});
答案 0 :(得分:1)
我无法建议什么对您最有利,因为我无法根据提供的信息正确显示您的数据。但是如果您在Backbone源中观察集合构造函数:
if (options.model) this.model = options.model;
然后在_prepareModel:
var model = new this.model(attrs, options);
我们知道“模型”无论如何都是一个函数,函数可以返回你想要的东西。因此,提供两个不同的数据源具有一些可以识别它们的属性,您可以执行以下操作:
var SkillModel = Backbone.Model.extend({
sayMyName: function() {
return 'I am a skill model and I am skilled at ' + this.get('name');
}
});
var LocationModel = Backbone.Model.extend({
sayMyName: function() {
return 'I am a location model and I am relaxing in ' + this.get('name');
}
});
function FilterModel(attrs, options) {
if (attrs.type === 'skill') {
return new SkillModel(attrs, options);
} else if (attrs.type === 'location') {
return new LocationModel(attrs, options);
}
}
var FilterCollection = Backbone.Collection.extend({
model: FilterModel
});
var filteredCollection = new FilterCollection([{
type: 'skill',
name: 'carpentry'
}, {
type: 'location',
name: 'India'
}, {
type: 'skill',
name: 'plumbing'
}]);
var outputEl = document.querySelector('#output');
filteredCollection.each(function(model) {
outputEl.innerHTML += '<p>' + model.sayMyName() + '<p>';
});
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div id="output"></div>