2013-05-07 3 views
5

BackboneJS를 사용하여 하위 뷰에서 뷰 기능을 호출 할 수 있는지 알고 싶습니다. 예인 경우 어떻게 작동합니까?BackboneJS를 사용하여 하위 뷰에서 뷰 기능 호출

하위 뷰에서 mainView에 속한 "hello"함수를 호출하려고합니다. 이벤트가 트리거 어쩌면 경우

...

예 :

var MainView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $(template); 
     this.subview = new SubView();    
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     var element = this.$template.attr('id'); 
     this.subview.setElement('#'+element).render(); 
    }, 

    hello: function() { 
     alert('Hello'); 
    } 

}); 


var SubView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $(template);   
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     //Call view function ' hello ' 
     //parentView.hello(); 
    } 

}); 

감사합니다!

당신은 당신의 서브 뷰에 부모 뷰에서 참조를 전달할 수 있습니다
+0

'var SubView = Backbone.MainView.extend'를 사용하여'MainView'를 확장 해 보았습니까? 그러면'SubView '에서'hello' 함수를 호출 할 수 있습니다. –

답변

8

:

http://jsfiddle.net/puleos/hecNz/

var MainView = Backbone.View.extend({ 

    initialize: function() { 
     this.$template = $("<span>foo</span>"); 
     this.subview = new SubView({parent: this});    
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     var element = this.$template.attr('id'); 
     this.subview.setElement('#'+element).render(); 
    }, 

    hello: function() { 
     alert('Hello'); 
    } 

}); 


var SubView = Backbone.View.extend({ 

    initialize: function(options) { 
     this.$template = $("<span>bar</span>"); 
     this.parent = options.parent; 
     this.render();    
    }, 

    render: function() { 
     this.$el.html(this.$template); 
     this.parent.hello(); 
    } 

}); 

var mainView = new MainView(); 

console.log(mainView); 
2

당신은 MainView 다음과 같이 확장 시도 할 수 있습니다 :

var SubView = MainView.extend({ });

그 다음해야 MainView 내에 hello 함수에 대한 참조를 제공하십시오.

또는 SubView에, 당신의 render 기능이 추가

MainView.prototype.hello.call(this) 

SubView 인스턴스의 컨텍스트 (템플릿, 기타 바르 등)를 사용하여 MainViewhello 함수를 호출 할 것이다.

+0

이것은 작동하지만 hello를 정적 메서드로 호출합니다. SubView를 만든 MainView 인스턴스의 상태에 액세스 할 수 없습니다. –

+0

그는 부모보기의 상태에 액세스하려고합니까? –

+2

적어도 현재는 정적 호출과 비교하여 참조/옵션 메소드를 사용해야 할 때를 알고 있습니다. –

관련 문제