根据屏幕尺寸显示 Backbone.js 集合的子集
Displaying subset of Backbone.js collection depending on Screen Size
我在 Backbone.js 之上使用 Marionette,我想显示集合的一个子集,显示的项目数取决于浏览器宽度。
Example: 20 items in collection. Each ItemView shows in a 100px wide div.
If the browser width is <= 600px, only display 5, etc.
我会在两侧都有按钮来更改视图表示的索引,以便在数组中开始显示。
我可以获取数组的子集,使用循环遍历起始索引 -> 显示的数量和 Collection.at(i)。
//var collection already exists
var subset = new Collection();
var N = floor( screenwidth / 100 );
for(var i = index; i< index+N; i++){
subset.add(collection.at(i));
}
如何将屏幕宽度传递给渲染函数,以及如何在屏幕尺寸发生变化时重新渲染? jquery 对调整大小事件的绑定会有所帮助吗?
(注意:显示逻辑的数字并不完全正确,因为我还不知道与屏幕上的其他元素相比多少是最好的)
谢谢!
我建议您使用另一种方法:
- 添加表示当前项目对您的可见性的布尔属性
Collection的模特。
- 根据该属性更改可见性(通过 CSS
display
属性) DOM 元素在适当视图的 render
方法中。
因此代码可能如下所示:
var MyModel = Backbone.Model.extend({
defaults: {
...
display: true
},
...
});
var MyCollection = Backbone.Collection.extend({
model: MyModel,
...
});
var MyItemView = Backbone.View.extend({
model: MyModel,
...
render: function() {
if (this.model.get('display'))
this.$el.html( this.template( this.model.toJSON() ) ).show();
else
this.$el.hide();
},
...
});
var MyCollectionView = Backbone.View.extend({
collection: MyCollection,
...
initialize: function() {
$(window).resize(_.bind(this.resize, this));
},
resize: function() {
...
var N = floor(screenwidth / 100);
this.collection.each(function(model, i) {
model.set('display', i < N);
});
},
...
});
我在 Backbone.js 之上使用 Marionette,我想显示集合的一个子集,显示的项目数取决于浏览器宽度。
Example: 20 items in collection. Each ItemView shows in a 100px wide div.
If the browser width is <= 600px, only display 5, etc.
我会在两侧都有按钮来更改视图表示的索引,以便在数组中开始显示。
我可以获取数组的子集,使用循环遍历起始索引 -> 显示的数量和 Collection.at(i)。
//var collection already exists
var subset = new Collection();
var N = floor( screenwidth / 100 );
for(var i = index; i< index+N; i++){
subset.add(collection.at(i));
}
如何将屏幕宽度传递给渲染函数,以及如何在屏幕尺寸发生变化时重新渲染? jquery 对调整大小事件的绑定会有所帮助吗?
(注意:显示逻辑的数字并不完全正确,因为我还不知道与屏幕上的其他元素相比多少是最好的)
谢谢!
我建议您使用另一种方法:
- 添加表示当前项目对您的可见性的布尔属性 Collection的模特。
- 根据该属性更改可见性(通过 CSS
display
属性) DOM 元素在适当视图的render
方法中。
因此代码可能如下所示:
var MyModel = Backbone.Model.extend({
defaults: {
...
display: true
},
...
});
var MyCollection = Backbone.Collection.extend({
model: MyModel,
...
});
var MyItemView = Backbone.View.extend({
model: MyModel,
...
render: function() {
if (this.model.get('display'))
this.$el.html( this.template( this.model.toJSON() ) ).show();
else
this.$el.hide();
},
...
});
var MyCollectionView = Backbone.View.extend({
collection: MyCollection,
...
initialize: function() {
$(window).resize(_.bind(this.resize, this));
},
resize: function() {
...
var N = floor(screenwidth / 100);
this.collection.each(function(model, i) {
model.set('display', i < N);
});
},
...
});