我有一个滑块,每张幻灯片包含6个视频,因此我有一个视频集。
现在我需要将集合拆分成块,每6个视频,并为每个块(幻灯片)渲染一个视图。
我对此感到有点困惑,因为我是Backbone的新手,我发现很少有一种“正确”的方式在Backbone中做事。
我的解决方案:(感谢 Josh Leitzel )
第一张幻灯片显示3个视频,每隔6个
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)
答案 0 :(得分:4)
您的主要组件是slideView
。每个slideView
都有自己的视频集合 - 即,您可以将videosCollection
拆分为许多较小的集合,每个集合大小为6,然后为每个集合创建视图。
我写了一些代码,指出你正确的方向。您可以查看实时示例here。
// 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');