DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

Append child view outside parent view in DOM in Backbone.js app

In my backbone app I create a popover in parent view and add it to the DOM like this

afterRender: function() {
    this.$el.append(
      new Popover.Views.Default({ 
        stick:'right', 
        offsetTop: 3, 
        offsetRight: 5, 
        content: "Foo", 
        reference: this.$el
     }).render().$el
   );
},
toggle: function(){  
  app.vent.trigger('popover34:toggle');
}

However the popover is appended to its parent view. The parent view is a link and this causes some css issues in the popover.

My question is, is it safe to do something like:

afterRender: function() {
    $('body').append(
      new Popover.Views.Default({ 
        stick:'right', 
        offsetTop: 3, 
        offsetRight: 5, 
        content: "Foo", 
        reference: this.$el
     }).render().$el
   );
}

Or is there a way to set it just beside the parent view? The problem is that when I toggle the popover it will be added to the DOM multiple times.

Upvotes: 0

Views: 652

Answers (2)

aaronfay
aaronfay

Reputation: 1692

To second (and hopefully clarify) Isaac's answer here, your 'parent' view should be in one region, the Popover view should be in another region.

Brian Mann has done an excellent set of videos on Marionette.js and good application design, one specifically that demonstrates your exact scenario.

Good luck, Aaron

Upvotes: 1

Isaac Suttell
Isaac Suttell

Reputation: 469

It looks like you're using Marionette. Using Marionette, one way to handle this is with regions. From the docs:

Regions provide a consistent way to manage your views and show / close them in your application. They use a jQuery selector to show your views in the correct place.

You can put your region anywhere you like and trigger it using the Event Aggregator. In addition, it automatically closes old views so you don't end up with zombies.

Upvotes: 1

Related Questions