2012-07-25 3 views
13

Marionette.CompositeView에서 컬렉션을 정렬하려고합니다.CompositeView에서 컬렉션을 정렬하는 가장 좋은 방법

[ 
    {id: 1, name: 'bar'}, 
    {id: 2, name: 'boo' }, 
    {id: 3, name: 'foo' } 
] 

내가 역순 ID로 컬렉션을 정렬 할 필요
나는 다음과 같다 컬렉션이 있습니다.
실제로 페이지를 새로 고침 할 때만 작동합니다.
새 모델을 추가하면 새 항목이 목록에 임의로 추가됩니다.
페이지를 새로 고치면 잘 분류됩니다.

내 질문은 :
1) 새 모델을 추가 할 때 문제를 해결하는 방법?
2) 코드를 개선 할 수 있습니까? 당신이 컬렉션을 만들 때

return Marionette.CompositeView.extend({ 

    initialize: function() { 
     this.collection.fetch(); 
    }, 

    onRender: function() { 
     var collection = this.collection; 

     collection.comparator = function (collection) { 
      return - collection.get('id'); 
     } 
    }, 

    onSuccess: function() { 
     this.collection.add(this.messageModel); 
     this.collection.sort(); // the messageModel seems to be added 
           // apparently randomly to the list. 
           // only if I refresh the page it will be ok 
    } 
}) 

답변

1

당신이 .comparator를 선언 할 수 있습니다 : 여기


내 코드? 귀하의 코드에서 .comparator는 지역 변수 var collection onRender 함수 내에 만 존재합니다. 올바르게 정의하면 컬렉션이 자동으로 정렬 할 수 있어야하며 마리오네트 경우> = 2.0, CollectionViewCompositeView maintain sorting by default을 새로운 모델

var Chapters = new Backbone.Collection({ 
    comparator = function(chapter) { 
     return chapter.get("id"); 
    }; 
}); 
14

를 추가 한 후 .sort 호출 할 필요는 없습니다. 네트 들어 < 2.0

및> = 1.3.0 :

네트 용
var MySortedView = Backbone.Marionette.CollectionView.extend({ 

    // ... 

    appendHtml: function(collectionView, itemView, index) { 
    // Already sorted when buffering. 
    if (collectionView.isBuffering) { 
     Backbone.Marionette.CollectionView.prototype.appendHtml.apply(this, arguments); 
    } 
    else { 
     var childrenContainer = $(collectionView.childrenContainer || collectionView.el); 
     var children = childrenContainer.children(); 
     if (children.size() === index) { 
     childrenContainer.append(itemView.el); 
     } else { 
     childrenContainer.children().eq(index).before(itemView.el); 
     } 
    } 
    } 

}); 

< 2.0 < 1.3.0 (전에 버퍼링없이 동일)

var MySortedView = Backbone.Marionette.CollectionView.extend({ 

    // ... 

    appendHtml: function(collectionView, itemView, index) { 
    var childrenContainer = $(collectionView.childrenContainer || collectionView.el); 
    var children = childrenContainer.children(); 
    if (children.size() === index) { 
     childrenContainer.append(itemView.el); 
    } else { 
     childrenContainer.children().eq(index).before(itemView.el); 
    } 
    } 

}); 

CollectionView와 CompositeView도 같습니다.

+0

GitHub의 링크가 – ErichBSchulz

+0

는 GitHub의 링크가 더 이상 죽은입니다 .. 아주 잘 작동 발견 됐어요 죽은. – Ziggy

+1

Github의 링크가 다시입니다 :-) 죽은 :-( – abhaga

3

나는 마리오 네트 대원들이 이것을 마리오 네트로 만들기를 고려하고 있다고 생각하지만, 그때까지 Sorted이라는 약간의 믹스 인을 만들었습니다.이 믹스는 CollectionViewCompositeView 클래스에 혼합 할 수 있습니다. 그것은 크게 오랫동안 Gitter에 대한 생산 환경에서 사용하고 우리는