我是Backbone的新手。
我正在寻找适合我情况的设计模式。
目前我有一个View模板,其中包含多个html选择:
<select id="s1"></select>
<select id="s2"></select>
<select id="s3"></select>
....
使用不同的JAX-RS API路径填充select
多个Backbone集合。
var C1 = Backbone.Collection.extend({
url='/path1'
});
var C2 = Backbone.Collection.extend({
url='/path2'
});
...
直接的方法是使用像this这样的解决方案:
render: function(){
var that = this, promises = [],
c1 = new C1(), c2 = new C2(), c3 = new C3();
promises.push(c1.fetch());
promises.push(c2.fetch());
promises.push(c3.fetch());
...
$.when.apply(null, promises).done(function(){
that.$el.html(FormTemplate({c1m: c1.models, c2m: c2.models, c3m: c3.models, ...}));
});
return this;
}
但是,这将涉及从客户端到Java服务器的几个API调用。有没有办法只用一次API调用就可以实现这个目的?
感谢。
答案 0 :(得分:1)
显然,API应该提供一条返回所有数据的路由。然后,您可以使用单个集合来获取它,并将过滤后的数据传递给其他集合,而无需进行API调用。
类似的东西:
var SingleEndPointCollection = Backbone.Collection.extend({
url = '/singleEndPoint'
});
var C1 = Backbone.Collection.extend({});
var C2 = Backbone.Collection.extend({});
var C3 = Backbone.Collection.extend({});
var view = Backbone.View.extend({
initialize: function() {
var that = this;
this.collection = new SingleEndPointCollection();
this.collection.fetch({
success: function(collection, response) {
that.c1 = new C1(collection.filter(function() {
// your logic here
}));
that.c2 = new C2(collection.filter(function() {
// your logic here
}));
that.c3 = new C3(collection.filter(function() {
// your logic here
}));
that.render();
}
});
},
render: function() {
var that = this;
that.$el.html(FormTemplate({
c1m: that.c1.toJSON(),
c2m: that.c2.toJSON(),
c3m: that.c3.toJSON()
}));
return this;
}
});