2013-05-18 5 views
5

나는 백본으로 놀고 있었고 그것을 배우려고 노력했다. 나는이 시점에서 잠시 머물러있다. 다음 코드의 문제점을 파악할 수 없습니까?이 렌더링 기능이 작동하지 않는 이유는 무엇입니까?

render: function() { 
    this.$el.empty(); 
    // render each subview, appending to our root element 
    _.each(this._views, function(sub_view) { 
     this.$el.append(sub_view.render().el); // Error on this line 
    }); 

답변

11

문맥 문제가 발생했습니다. 당신이 찾고있는 this은 찾고있는 $el을 포함하고 있지 않습니다. 적절한 this을 가리키는 self 변수를 선언하여이 문제를 해결할 수 있습니다. 다음 코드가 도움이 될 것입니다.

render: function() { 
    var self = this; //Added this line to declare variable (self) that point to 'this' 
    this.$el.empty(); 
    _.each(this._views, function(sub_view) { 
     self.$el.append(sub_view.render().el); //Used 'self' here instead 'this' 
}); 

사이드 참고 : 백본을 기울고으로 또한 문서 리플 로우와 매우 commong 자바 스크립트 문제에 대해 알고 있어야합니다. 컬렉션의 모든 단일 모델에 대한 뷰를 렌더링합니다. 성능 문제가 발생할 수 있으며, 특히 오래된 컴퓨터와 모바일 장치에서 발생할 수 있습니다. 매번 DOM을 업데이트하지 않고 모든 내용을 container에 렌더링하고 한 번 추가하면 코드를 최적화 할 수 있습니다. 예를 들면 다음과 같습니다.

render: function() { 
    this.$el.empty(); 
    var container = document.createDocumentFragment(); 
    _.each(this._views, function(sub_view) { 
    container.appendChild(sub_view.render().el) 
    }); 
    this.$el.append(container); 
} 
+0

완벽한 작품입니다! 고마움을 많이 전하며 또한 문서 흐름 문제를 염두에 두겠습니다. 정말로 유용한 정보! –

관련 문제