2012-03-03 88 views
3

我有一個滑塊,每個幻燈片包含6個視頻,所以我有一個視頻集合。Backbone.js分割集合分塊

現在我需要將集合拆分成塊,每個視頻6個,併爲每個塊(幻燈片)渲染一個視圖。

我對此有點困惑,因爲我是Backbone的新手,我發現很少有在Backbone中做「正確」的事情。

我的解決方案:(感謝喬希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) 

回答

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'); 
+0

非常感謝,我發佈了我想出的以上內容 – 2012-03-04 11:25:05