2012-03-07 2 views
2

아래 코드를 작동시키는 데 문제가 발생했습니다.Backbone.js보기 안의보기에서 이벤트 실행

고유 한 이벤트 객체가있는 렌더링 된 하위보기에서 이벤트를 실행하려고합니다.

쉬운 방법으로이 작업을 수행 할 수 있습니까?

var SubView = Backbone.View.extend({ 
    events: { 
     'click .subview-item a': 'test' 
    }, 
    el: '#subview', 
    test: function() { 
     console.log('please print this...'); 
    }, 
    initialize: function() { 
     this.template = '<div class="subview-item"><a href="#">Clickable Subview</a></div>' 
    }, 
    render: function(){ 
     $(this.el).html(_.template(this.template)); 
     return this; 
    } 
}); 

var MainView = Backbone.View.extend({ 
    el: $('#content'), 
    initialize: function(){ 
     this.template = '<h1>Hello</h1><div id="subview"></div>'; 
     this.subView = new SubView(); 
    }, 
    render: function(){ 
     $(this.el).html(_.template(this.template)); 
     this.subView.render(); 
     return this; 
    } 
}); 

var mainView = new MainView({}); 
mainView.render(); 

어떤 아이디어 ??

답변

6

당신이 아직 렌더링되지 않았기 때문에 MainViewinitialize 내부 subView#subview 요소가 아직, 당신의 DOM에 존재하지 않는 MAINVIEW을 만들 때. 따라서 새 <div>외부에 DOM으로 생성됩니다. SubView을 만들기 전에 먼저 MainView을 렌더링해야합니다. 당신은 할 수 그 내부의 MainViewrender()하지만 다음 내가 생각하는 간단하다 :

var SubView = Backbone.View.extend({ events: { 'click .subview-item a': 'test' }, el: '#subview', test: function() { console.log('please print this...'); }, initialize: function() { this.template = _.template('<div class="subview-item"><a href="#">Clickable Subview</a></div>'); }, render: function() { this.$el.html(this.template); return this; } }); var MainView = Backbone.View.extend({ el: $('#content'), initialize: function() { this.template = _.template('<h1>Hello</h1><div id="subview"></div>'); }, render: function() { this.$el.html(this.template); return this; } }); var mainView = new MainView(); mainView.render(); var subView = new SubView(); subView.render(); 

는 또한 this.$el을 사용하고 initialize()에 템플릿을 만드는 것이 아니라 모든에 재 컴파일과 같은 몇 가지를 해결하기 위해 자유를했다 render().