gpt4 book ai didi

Backbone.js 将集合拆分为 block

转载 作者:行者123 更新时间:2023-12-01 12:56:32 24 4
gpt4 key购买 nike

我有一个 slider ,每张幻灯片包含 6 个视频,所以我有一个视频集。

现在我需要将集合分成 block ,每 block 6 个视频,并为每个 block 呈现一个 View (一张幻灯片)。

我对此有点困惑,因为我是 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)

最佳答案

您的主要组件将是一个slideView。每个 slideView 都有自己的视频集合——也就是说,您可以将 videosCollection 分成许多较小的集合,每个集合大小为 6,然后为每个集合创建 View .

我已经编写了一些代码,应该可以为您指明正确的方向。您可以查看一个实例 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');

关于Backbone.js 将集合拆分为 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9548629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com