[英]Backbone.js accessing another view function
I'm developing an application with Backbone.js 我正在使用Backbone.js开发一个应用程序
I have 2 view and I want use a function defined in other view: 我有2个视图,我想使用在其他视图中定义的函数:
var FormView = Backbone.View.extend({
initialize: function(){
resultsView.myFunction();
}
})
var resultsView = Backbone.View.extend({
myFunction: function(){
alert('test')
}
})
How I can do it? 我怎么能这样做?
You're doing it the opposite way. 你正在以相反的方式做到这一点。 You can do a
base view
that other views can extend and implement such as: 您可以执行其他视图可以扩展和实现的
base view
,例如:
/** Any Views that inherit from this View can use the myFunction() */
var BaseView = Backbone.View ({
myFunction : function(param) {
alert(param);
}
});
/** Inherit from the base view above */
var ChildView = BaseView.extend({
initialize : function(){
this.myFunction('test');
}
});
var instanceView = new ChildView({});
why not use events? 为什么不使用活动?
When you use Backbone.View.extend
, you are creating a class
. 当您使用
Backbone.View.extend
,您正在创建一个class
。 In order to use the class, you need to create an instance
using the new
operator. 要使用该类,您需要使用
new
运算符创建instance
。 It's conventional to start class names with a Capital letter, and instance variable names with a small letter, so I'll use that naming convention in the following samples: 通常使用大写字母和带小写字母的实例变量名称来启动类名,因此我将在以下示例中使用该命名约定:
//declare view class
var ResultsView = Backbone.View.extend({
myFunction: function(){
alert('test')
}
});
Create an instance of the class, and pass it into your FormView
: 创建类的实例,并将其传递给
FormView
:
var resultsView = new ResultsView();
var formView = new FormView({ resultsView: resultsView });
Access the passed argument in the FormView.initialize
: 访问
FormView.initialize
传递的参数:
var FormView = Backbone.View.extend({
initialize: function(options){
options.resultsView.myFunction();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.