2014-03-24 2 views
0

항목 목록을 렌더링하기위한 Backbone.js보기를 만들 계획입니다. 목록이 늘어납니다. 성능상의 이유로 항목을 비우고 DOM을 다시 작성하면 안됩니다. 이게 말이 돼? 어떻게이 접근합니까?Backbone.js 목록을 부분적으로 렌더링 하시겠습니까?

+0

당신은 각 목록 항목에 대한 하나 개의보기를 사용하고 있습니까? 또는 컬렉션에 대한 하나의보기? 당신의 명부는 변화하고 있는가 또는 다만 성장하고 있는가? 단지 성장하는 경우 전체 목록을 다시 렌더링하는 대신 항목을 추가 할 수 있습니다. – Jack

답변

1

이러한 종류의 일반적인 설치 방법은 ul에 대한 Backbone.View 또는 내가 가지고있는 요소가 들어있는 요소를 정의하고이를 컬렉션에 바인딩하는 것입니다. 그런 다음 다른 Backbone.View를 정의하여 단일 목록 항목을 렌더링합니다. 이 뷰의 인스턴스는 컬렉션의 모델과 일대일 관계를 유지합니다.

컬렉션에는이를 반영하기 위해 수행해야하는 다양한 유형의 DOM 작업과 잘 어울리는 서로 다른 이벤트가 있습니다. 나는 이런 식으로 매핑 :.

  • 동기화 =
  • 추가 =이 $의 APPEND (...)
  • 제거는 = [해당 찾을 목록보기 항목] .remove [최초 인출에 대한 전체 목록을 렌더링]()

좋아, 그럼이 코드는 단지 메모리에서 내려 망치로하지 테스트,하지만 당신은 아이디어를 얻을 수있다 :

var collection = new Backbone.Collection({ 
    model: Backbone.Model, 
    url: '/some/api/endpoint' 
}); 

var Li = Backbone.View.extend({ 
    tagName: 'li', 
    initialize: function(){ 
    this.render(); 
    }, 
    render: function(){ 
    var template = _.template($('li-template').html()); 
    this.el = template(model.toJSON()); 
    } 
}); 

var Ul = Backbone.View.extend({ 
    collection:collection, 
    el: 'ul', 
    initialize: function(){ 
    this.listItems = []; 
    this.collection.on('sync', this.addAll); 
    this.collection.on('add', this.addOne); 
    this.collection.on('remove', this.removeOne); 
    }, 

    addAll: function(){ 
    var frag = document.createDocumentFragment(); 
    this.collection.forEach(function(model){ 
     var view = new Li({model: model}); 
     frag.appendChild(view.el); 
     this.listItems.push(view); 
    }); 
    this.el.appendChild(frag); 
    }, 

    addOne: function(model){ 
    var view = new Li({model: model}); 
    this.el.appendChild(view.el); 
    this.listItems.push(view); 
    }, 

    removeOne: function(model){ 
    for (var i = 0, num = this.listItems.length, item; i < num; i++) { 
     view = this.listItems[i]; 
     if (view.model.cid === model.cid) { 
     this.el.removeChild(view.el); 
     this.listItems.splice(i, 1); 
     } 
    } 
    } 
}); 
+0

문제가 해결되면 대답을 승인으로 표시하십시오. – nordhagen

관련 문제