2013-05-07 41 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'函數。 – 2013-05-08 15:04:20

回答

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實例的上下文(模板,其他增值經銷商等)調用hello功能MainView

+0

這可行,但它是作爲靜態方法調用hello。它將無法訪問創建SubView的MainView實例的狀態。 – 2013-05-08 12:17:19

+0

他甚至想訪問父視圖的狀態嗎? – 2013-05-08 15:10:20

+2

不知道,但至少現在他知道何時使用reference/options方法與靜態調用。 – 2013-05-08 15:18:26