2016-07-05 2 views
1

부모 뷰가 있고 부모 html 내부에 하위 뷰 렌더링 중 뷰가 있습니다. 자식보기는 부모 html 내에 에 배치 된 버튼을 클릭 할 때 반복 가능합니다. 그러나 내부에서 버튼 클릭 이벤트가 발생하지 않습니다. 버튼 HTML과 같은 하위 뷰 이벤트는 상위 HTML 내부에 있습니다. 하위 뷰 내에서 클릭 이벤트를 얻으려면 어떻게해야합니까?하위 뷰 내에서 상위 뷰 이벤트 가져 오기

JS :

var parView = Backbone.View.extend({ 
    template: _.template($('#par').html()), 
    initialize: function(){ 
    this.render(); 
    }, 
    render: function() { 
     this.$el.html(this.template); 
     new childView({el:'#repeatable-child-sectn'}); 
     return this; 
    } 
}); 
var childView = Backbone.View.extend({ 
    template: _.template($('#child').html()), 
    events: { 
    'click #button': 'addChild' 
    }, 
    initialize: function(){ 
    this.render(); 
    }, 
    render: function() { 
     this.$el.html(this.template); 
     return this; 
    }, 
    addChild: function(){ 
     $('#repeatable-child-sectn').append(this.template); 
    } 
}); 

HTML :

<script type="text/template" id='par'> 
    <div id='par'> 
    <div id='repeatable-child-sectn'></div> 
    <div id='button'>Add Child</div> 
    </div> 
</script> 
<script type="text/template" id='child'> 
    <div>Child Section</div> 
</script> 

우리 아이 뷰 내부의 상위 이벤트를받을 수 있습니까?

나는 약간 다른 접근 방식을 부모 뷰는 '아이를 추가'버튼 클릭을 수신뿐만 아니라, 인스턴스 및 추가 아이 뷰를 관리함으로써 사물을 단순화 할
+0

접근 방법이 잘못되었습니다. "자녀 추가"는 자녀가 아닌 부모의 기능이어야합니다. 또한 다중 뷰 인스턴스는 같은 요소를 가르키면 안된다 –

답변

2

:

var ParentView = Backbone.View.extend({ 
    template: _.template($('#par').html()), 
    events: { 
    'click #button': 'addChild' 
    }, 
    initialize: function() { 
    this.childViews = []; // keep track of childviews in case they need to be removed, etc. 
    }, 
    render: function() { 
    this.$el.html(this.template); 
    return this; 
    }, 
    addChild: function() { 
    var childView = new ChildView(); 
    this.childViews.push(childView); 
    this.$('#repeatable-child-sectn').append(childView.$el); 
    } 
}); 
var ChildView = Backbone.View.extend({ 
    template: _.template($('#child').html()), 
    initialize: function() { 
    this.render(); 
    }, 
    render: function() { 
    this.$el.html(this.template); 
    return this; 
    } 
}); 

JSFiddle을 : https://jsfiddle.net/9jms89n2/

+1

이 답변은'$ ('repeatable-child-sectn')'을 사용하는 것을 제외하면 좋다. ... 이상적으로 글로벌 선택자가 없어야한다. 또한 자식보기 자체 렌더링 할 수 있습니다 ... –

관련 문제