Backbone.js - Binding from one view to another?
Asked Answered
B

2

5

I have a main app view, with a filter menu in the header. When it's clicked, I want to filter content in a seperate news-feed view. But I don't know how to bind events (and pass class data) from clicks in one view to a function in another.

How can I accomplish this?

Bier answered 3/8, 2011 at 17:30 Comment(0)
E
16

There are a number of ways to accomplish this, but probably you want to create a model object, which is shared between the two views. Then on 'click' in view one, update the model object, and bind 'on change' in view two to the model object.

Basically, you can set up both views to stay in sync with the model object, and any changes to the object will result in changes to the view.

Ecclesiastes answered 3/8, 2011 at 18:19 Comment(6)
+1 This is definitely in line with the philosophy of Backbone.Bellwether
+1 Seems like the way to go but what if I already have a model being used in the view? also what if the views I want to interact are parent and child (child views are nested inside parent)?Hunkers
I also found that event aggregator mentioned here works well too - lostechies.com/derickbailey/2011/07/19/…Hunkers
Derick Bailey revisited the event aggregator - lostechies.com/derickbailey/2012/04/03/…Aidoneus
I don't like this solution. It creates tight coupling between components. This is considered as antipattern.Ecstatics
@Ecstatics How is this an anti-pattern?Crenation
L
2

Everything in Backbone inherits from Backbone.Events, so you can trigger and bind events from anywhere (docs for Backbone.Events):

var View1 = Backbone.View.extend();

var View2 = Backbone.View.extend({
    eventHandler: function(data) {alert(data)}
});

var v1 = new View1;
var v2 = new View2;

v1.bind('hello-world-event', v2.eventHandler)
v1.trigger('hello-world-event', 'Hello World!')

Note that in this example, when v2.eventHandler is called, 'this' will refer to v1. See the backbone docs for more.

Linctus answered 3/8, 2011 at 18:47 Comment(3)
What if I don't have two instance variables of the views in the same .js file?Bier
Well, as regards app structure, you have a bunch of options, as idbentley pointed out. For instance, you could have a 'controller'-like app view that instantiates some subviews, listens for events, and dispatches accordinglyLinctus
Example doesn't follow question. You're triggering event on the same View, which is "catching" the event.Ecstatics

© 2022 - 2024 — McMap. All rights reserved.