I'm trying to render a subview within a view in Backbone. I'm following this example:
http://backbonetutorials.com/examples/modular-backbone/
which seems to work fine. This is my code for the parent view:
define([
'jquery',
'underscore',
'backbone',
'models/products/ProductsModel',
'views/products/ProductsFiltersView',
'text!templates/products/productsTemplate.html',
], function($, _, Backbone,ProductsModel,ProductsFiltersView,productsTemplate){
var ProductsView = Backbone.View.extend({
el: $("#page"),
initialize: function(){
var self = this;
self.model = new ProductsModel();
},
render: function(){
var pageTitle = this.model.get('title');
document.title = pageTitle;
var pageData = {
title: pageTitle
}
var compiledTemplate = _.template( productsTemplate ); //prerender template
this.$el.html(compiledTemplate(pageData));
this.renderFiltersView();
},
renderFiltersView: function(){
var productsFiltersView = new ProductsFiltersView();
productsFiltersView.render();
}
});
return ProductsView;
});
And this my code for the subview:
define([
'jquery',
'underscore',
'backbone',
'text!templates/products/productsFiltersTemplate.html',
], function($, _, Backbone,productsFiltersTemplate){
var ProductsFiltersView = Backbone.View.extend({
el: $(".filters.product"),
events : {
"click .filter-options-container" : "filterOptionContainerClick"
},
initialize: function(){
var self = this;
},
render: function(){
var compiledTemplate = _.template( productsFiltersTemplate ); //prerender template
this.$el.html(compiledTemplate()); //this.$el.length = 0;
//$(.filters.product').html(compiledTemplate()) //this works
this.inlineSVG($('.filter-option')); //need to convert img tags to inline svg so we can manipulate their fill color dynamically
}
})
return ProductsFiltersView;
});
No errors are being thrown, and if I change the this.$el.html in the subview to an action jquery selector, the view is rendered, but I want to fix the overall problem, which is that this view is being instantiated before the parent view's DOM contents are ready. Anyone know what I'm doing wrong?
--EDIT--
Here is my parent template
<div class="page-container products cf">
<div class="products-and-filters">
<div class="products-container">
</div>
<div class="filters product">
</div>
</div>
<div class="wishlist products">
</div>
</div>
Try
this.setElement(".filters.product")
in initialize method of subview