2013-05-07 39 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