I'm developing an application with Backbone.js
I have 2 view and I want use a function defined in other view:
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:
/** 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
. In order to use the class, you need to create an instance
using the new
operator. 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
:
var resultsView = new ResultsView();
var formView = new FormView({ resultsView: resultsView });
Access the passed argument in the FormView.initialize
:
var FormView = Backbone.View.extend({
initialize: function(options){
options.resultsView.myFunction();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.