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?
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?
Share Improve this question edited May 5, 2015 at 14:28 Arslan Ali 17.8k9 gold badges63 silver badges83 bronze badges asked Feb 25, 2013 at 17:20 ValerianeValeriane 9543 gold badges17 silver badges39 bronze badges 1- In general, You don't want to do that. You'll end up with spaghetti code. If it's a general function, abstract it out. If the function really does have to do with something that resultsView should be concerned with, then listen for changes in the model or trigger an event on formView that resultsView listens to. – steveax Commented Feb 25, 2013 at 17:35
3 Answers
Reset to default 5You'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?
routing-and-the-event-aggregator-coordinating
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();
}
});