Trunk - view of the parent view of the call / link from the child view

I am new to Backbone and I would like to know how to do it. I would like for an easy way to contact the parent view from the child, that is, call the method on the parent.

The following is an example of an example using the desktop and document views:

class DesktopView extends Backbone.View{ constructor(options?) { super(options); this.el = $('#desktop'); this.createDocument(); } createDocument() { dv = new DocumentView(); $(this.el).append(dv.render()); } } class DocumentView extends Backbone.View{ constructor(options?) { super(options); this.tagName = 'div'; this.className = 'document'; this.events = { "click": "clickHander" }; }; render() { return this.el; } clickHandler() { //COMMUNICATE WITH THE DESKTOP VIEW } } 

Should I create a model to represent the document and listen to the changes in this?

+7
source share
2 answers

You can use Backbone events to call functions. This has the advantage that the "child" view does not have to know the parent about it.

 var parent = Backbone.View.extend({ initialize : function () { this.listenTo( Backbone, 'child-click-event', function ( dataFromChild ) { this.doSomething( dataFromChild ); }, this ); } }); var child = Backbone.View.extend({ //... clickHandler : function () { var data; // do something and get data // Parent listens to this event. Backbone.trigger('child-click-event', data ); } }); 
+15
source

If you do not need a model, I would suggest passing the link to the parent view through the parameters of the child view. If you need a model, then listen to the changes on it through the parent view. I am not familiar with typescript, but you want to do something like this:

 createDocument() { that = this; // give reference to parent view dv = new DocumentView({desktopView : that}); $(this.el).append(dv.render()); } 

Then you should have access to it in child form, for example:

 this.options.desktopView 
+1
source

All Articles