Reputation: 363
I have my views seperated into separate files. In my main view I am trying to call a function in another view. Is there a way to do this in Backbone.js?
Upvotes: 1
Views: 1297
Reputation: 3568
A good way would be to use the Mediator pattern so you do not tightly couple your views.
In the latest versions of Backbone, the Backbone
object can be used as a mediator.
In view 1: Backbone.trigger('somethingHappened', {id: 1});
In view 2:
//action when 'something' happens
onSomething : function(data){
console.log('Got that: ' + data.id)
}
//... in the view init ...
Backbone.on('somethingHappened', onSomething)
//... in the view destruction...
Backbone.off('somethingHappened', onSomething);
You may also use the more recent listenTo
method.
Of course it will only work if view2 has been initialized.
Upvotes: 3