Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbonejs: is passing a parent's element reference to a child view a good practice?

giving a parent and a child view, I'd like 2 things:

  • the child view should render itself on instantiation
  • the child's render method should know the current parent's dom element

In practice, from the parent view, instead of this:

,add_bannerbox_view:function(model, collection, options){
    var bannerbox = new BannerBoxView({ model: model });
    this.bannerbox_views[model.cid] = bannerbox;
    this.bannerbox_container.append(bannerbox.el);
    bannerbox.render();
}

I'd like simply this;

    ,add_bannerbox_view:function(model, collection, options){
        //here, BannerBoxView is supposed to render itself from initialize() 
        this.bannerbox_views[model.cid] = new BannerBoxView({ model: model, parent:this.el });
    }

But I was wondering: is passing a parent's elem to the child a good practice? Or does it have some bad drawback?

like image 615
Luca Reghellin Avatar asked Dec 01 '25 18:12

Luca Reghellin


1 Answers

Loose coupling is almost always preferable to tight coupling. The two best reasons I can think of are:

  • Reusable. Can be used by anywhere in your app without worrying about dependencies.
  • Testable. Can be tested independent of other components.

By requiring the child view to have a reference to the parent view, you are promoting tight coupling i.e. the child view becomes dependent on the parent view. This makes reusability extremely difficult, and if you're writing unit tests, you're going to have to instantiate or mock a parent class just so you can test the child. This is unnecessary and tedious.

If really what you're trying to do is have the child view automatically render, just extend the core Backbone.View and include a helper function that your parent views can call.

var MyView = Backbone.View.extend({
    renderChild: function(view, options) {
        var childView = new view(options);
        this.views[options.model.cid] = childView;
        this.$el.append(childView.el);
        childView.render();
    }
});

Then, you can define your parent views like so:

var ParentView = MyView.extend({
    add_bannerbox_view: function() {
        this.renderChild(BannerBoxView, {model: model});
    }
});

The helper function we made will let you instantiate, append and render your child views with a single line of code.

like image 187
anushr Avatar answered Dec 04 '25 07:12

anushr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!