Backbone.js将集合拆分为块
我有一个滑块,每个滑块包含6个视频,所以我有一个视频集合 现在,我需要将集合拆分为块,每个块有6个视频,并为每个块渲染一个视图(一张幻灯片) 我对此有点困惑,因为我对主干网还不熟悉,我发现主干网中很少有“正确”的做事方式 我的解决方案:(感谢Josh Leitzel) 第一张幻灯片显示3个视频,每隔6个Backbone.js将集合拆分为块,backbone.js,Backbone.js,我有一个滑块,每个滑块包含6个视频,所以我有一个视频集合 现在,我需要将集合拆分为块,每个块有6个视频,并为每个块渲染一个视图(一张幻灯片) 我对此有点困惑,因为我对主干网还不熟悉,我发现主干网中很少有“正确”的做事方式 我的解决方案:(感谢Josh Leitzel) 第一张幻灯片显示3个视频,每隔6个 render: -> $(@el).html(@template()) count = 0 passed_first_slide = false win
render: ->
$(@el).html(@template())
count = 0
passed_first_slide = false
window.slide = new Backbone.Collection()
for model in @collection.models
count++ if slide.add(model)
if !passed_first_slide
videos_per_slide = 3
else
videos_per_slide = 6
if count % videos_per_slide is 0
@appendVideoSlide(slide)
slide.reset()
passed_first_slide = true
count = 0 if videos_per_slide = 3
@setup()
this
appendVideoSlide: (slide) =>
view = new Etaxi.Views.VideoSlide(collection: slide)
$('ul#slider-videos').append(view.render().el)
您的主要组件将是一个
slideView
。每个slideView
都有自己的视频集合,也就是说,您可以将videoscolection
拆分为许多较小的集合,每个集合大小为6,然后为每个集合创建视图
我已经编写了一些代码,可以为您指出正确的方向。您可以查看一个实例
//要使用的基本主干元素
var videoModel=Backbone.Model.extend();
var videoscolection=Backbone.Collection.extend();
var slideView=Backbone.View.extend({
//注意:实际上这是一个糟糕的渲染函数,只是用来显示点
render:function(){
$('body')。追加('p>幻灯片:);
_.每个(此.collection.models、函数(视频){
$('body').append('li>'+video.get('name')+'');
});
$('body')。追加('
');
}
});
//创建35个视频的集合
var videos=新的videosCollection();
对于(var i=1;我非常感谢您,我已经发布了我在上面提出的内容
// Basic Backbone elements to work with
var videoModel = Backbone.Model.extend();
var videosCollection = Backbone.Collection.extend();
var slideView = Backbone.View.extend({
// Note: this is a terrible render function in practice, just used to show the point
render: function() {
$('body').append('<p>Slide:</p><ul>');
_.each(this.collection.models, function(video) {
$('body').append('<li>' + video.get('name') + '</li>');
});
$('body').append('</ul>');
}
});
// Create a collection of 35 videos
var videos = new videosCollection();
for (var i = 1; i <= 35; i++) {
videos.add(new videoModel({ name: 'Video ' + i }));
}
// Here's where the real partitioning comes in
var slides = [];
var numVideosPerSlide = 6;
var videosClone = new videosCollection(videos.models); // create a clone of the collection so we can manipulate it safely
while (videosClone.length > 0) {
// Pluck out the first X elements and add them to a new slideView
slides.push(new slideView({
collection: new videosCollection(videosClone.first(numVideosPerSlide))
}));
// Update the clone data to remove the elements we just added to slideView
videosClone = new videosCollection(videosClone.rest(numVideosPerSlide));
}
// Render each slideView
_.invoke(slides, 'render');