I'm new to Backbone and I'd like to know a best practice for this - I'd like an easy way to communicate with a parent view from a child i.e. call a method on the parent.
Rudimentary example below using "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 for the document view and listen for changes to that?
You could use Backbone events to trigger function calls. This has the advantage that a 'child' view does not have to know about it's parent.
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 );
}
});
If you don't NEED a model, I would suggest passing a reference to the parent view through the options to the child view. If you do need a model, then yes listen for changes on it through the parent view. I'm 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 be able to access it in the child view like:
this.options.desktopView
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