I've set up a project where I've extended a Backbone.Marionette.Layout
that contains two different regions. This layout can be used as a component throughout the application. In particular, the regions are set up like the following.
regions : {
masterRegion : { selector: '[data-region=master]' },
slaveRegion: { selector: '[data-region=slave]' }
},
In particular, I'm using a data-region
selector to inject the view I'm interested in.
When such a layout is used in a tree structure views are duplicated since getEl
function adresses the wrong region to inject the view. Obviously it's my fault and within Marionette
(v1.1.0) doc the following is written.
override the getEl function if we have a parentEl this must be overridden to ensure the selector is found on the first use of the region. if we try to assign the region's el to parentEl.find(selector) in the object literal to build the region, the element will not be guaranteed to be in the DOM already, and will cause problems
where getEl
is defined as
getEl: function(selector){
return Marionette.$(selector);
}
So, my question is the following. What does this mean? How can I override this method? Where is the correct to perform such an override?
Hope it's clear.
Here's my understanding of this:
In other words, the first time you use a region (e.g. with a call to the
show
method), Marionette needs to build a region instance and associate it with the correct DOM element (specified by theselector
attribute).However, before Marionette can look for the DOM element within the containing parent element, it must ensure that all required DOM elements (most importantly the one we're looking for) have loaded.
Does that make more sense to you?
Edit based on flexaddicted's comment.
I don't think you need to override this method. The comment indicates why the DOM element is fetched that way instead of by direct assignment when the region is built, but it should still work properly with a tree structure (since parents can still be determined properly).
I think the problem might be with your region selector: as it is "generic", it can potentially match multiple elements (as opposed to selecting with an
id
attribute that should match only 1 element), and could be matching a DOM element you're not expecting such as a child view. (This of course depends on when Marionette looks at the DOM to fetch the selector.)Also, I'd consider using a composite view for your tree structure needs if possible. See http://davidsulc.com/blog/2013/02/03/tutorial-nested-views-using-backbone-marionettes-compositeview/ and http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/