Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from one view to another with custom events?

Tags:

backbone.js

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.

like image 910
Running Turtle Avatar asked Apr 25 '11 22:04

Running Turtle


3 Answers

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.

like image 94
Mike Barlow - BarDev Avatar answered Oct 16 '22 06:10

Mike Barlow - BarDev


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);
like image 35
Andrew Hare Avatar answered Oct 16 '22 07:10

Andrew Hare


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.

like image 1
Joshua D. Boyd Avatar answered Oct 16 '22 06:10

Joshua D. Boyd