Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone - call / reference parent view from child view

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?

like image 922
user888734 Avatar asked Jun 12 '13 15:06

user888734


2 Answers

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 );
  }
});
like image 135
mor Avatar answered Oct 19 '22 06:10

mor


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
like image 25
Evan Avatar answered Oct 19 '22 06:10

Evan