0

I have a parent backbone view which creates a new backbone view in its render method.

var appView = Backbone.View.extend({
    ...
    render: function() {
        preview = new previewDataView({model: model, el: $el.find('.preview-container')});
    }
});

I want to be able to trigger a custom event in appView and have previewDataView bind to it -- is this possible? previewDataView did not receive the event when I tried that. Thoughts?

4

1 回答 1

2

Two ways I think you could accomplish this. First, pass the parent into the child view. Second, create an eventAggregator that handles event firing.

FIRST:

You could pass the appView into the previewDataView as an options.

preview = new previewDataView({ // your options, 'parent':this });

In your previewDataView you would bind to the parent custom event like so:

this.parent = this.options.parent;
this.parent.bind('eventName', this.onEvent, this);

SECOND: (Just learned this technique)

You could create an eventAggregator that helps your views subscribe to and unsubscribe for events meant for each other. Here is a good answer that explains this in detail on Stack: fire an event from one view to another in backbone

In the comments, @Brian Genisio takes it a step further to include this in his code:

Backbone.View.prototype.eventAggregator = _.extend({}, Backbone.Events);

Have this run in the start of your code and every view will have access to eventAggregator which will be your central hub for events that need to be triggered and received across views. You'd use it like this:

// Parent View
this.eventAggregator.trigger('someEvent');

// Child View
this.eventAggregator.bind('someEvent', this.function, this);

With this, you don't have to explicitly pass reference between views that need access to each other for event triggering and listening. This method has come in QUITE handy for me. :-)

于 2012-03-15T02:58:31.120 回答