2012-03-03 4 views
3

슬라이드 당 6 개의 비디오를 포함하는 슬라이더가 있으므로 비디오 컬렉션이 있습니다.Backbone.js 콜렉션을 청크로 분할

이제 모음을 각 6 개의 비디오 청크로 분할하고 각 청크 (슬라이드)에 대한보기를 렌더링해야합니다.

백본을 처음 접했기 때문에 약간 혼란스럽고 백본에서 일을하는 "올바른"방식은 거의 없다는 것을 알았습니다.

내 솔루션 : (감사 에 조쉬 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

대단히 감사합니다. 위에 나온 내용을 게시했습니다. –

관련 문제