Say I have a View that displays a search box with a submit button. When I click on the submit button how do i pass the value of the search box to another view ?
I tried:
In view 1, inside the submit callback : this.trigger('abc', $('#searchBox').val())
In view 2, in the initialize function: this.bind('abc', function(data){ console.log(data); })
but that does not seem to work: the custom event is fired but View 2 does not see it.
Here's a great article by Derick Bailley @ LosTechies.com: References, Routing, And The Event Aggregator: Coordinating Views In Backbone.js
This article discusses a simple solution using PubSub that is built in Backbone.JS. I agree with Derick when he mentions that views should be decoupled.
Unfortunately you can't bind this way - you will need to share a reference to view1 in view2:
var View2 = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'foo');
this.view1.bind('abc', this.foo);
},
foo: function(data) {
console.log(data);
}
});
This also means that at some point you need to set view1
on your instance of View2
so that you can bind against it.
If you don't want to pass the references around, simply bind the two views together in whatever container you are holding them in (i.e. another view or a controller):
var view1 = new View1();
var view2 = new View2();
view1.bind('abc', view2.foo);
I suggest using a PubSub framework in addition to backbone. MinPubSub is a popular choice. I use the jquery pubsub extension extracted from https://github.com/phiggins42/bloody-jquery-plugins.
Then, View 2 doesn't need a reference to View 1. To modify Andrew Hare's example, you would do:
var View2 = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'foo');
$.subscribe('abc', this.foo);
},
foo: function(data) {
console.log(data);
}
});
Then in View 1:
$.publish('abc', $('#searchBox').val());
Of course, with a pubsub system, you will probably want to use something better than "abc", perhaps instead choosing "searchBox:submit" as the topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With