我在 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.
我会在两侧都有按钮来更改数组中开始显示的 View 指示索引。
我可以使用起始索引 -> 显示数量和 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 绑定(bind)会有帮助吗?
(注意:显示逻辑的数字并不完全正确,因为我还不知道与其他屏幕元素相比有多少是最好的)
谢谢!
最佳答案
我建议您使用另一种方法:
- 添加 bool 属性,表示当前项目对您的可见性 收藏品模型。
- 根据该属性更改可见性(通过 CSS
display
属性)在适当的 View 的render
方法中的 DOM 元素。
所以代码可能如下所示:
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);
});
},
...
});
关于javascript - 根据屏幕尺寸显示 Backbone.js 集合的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29357464/