Search code examples
backbone.jsunderscore.jssubviews

How to set .el to div which is in underscore.js template?


It is pretty basic thing but I still can't find the answer. I need to set View's el: to div which is in underscore.js template.

<script id="product" type="text/template">
    <div class="productInfo"></div>
    <div class="prices"></div>
    <div class="photos"></div>
</script>

The first view renders the product template. I need to render other Views to divs in this template. I don't know how to set el:, because el: '.prices' just don't work with divs in template.

This Views structure is similar to How to handle initializing and rendering subviews in Backbone.js?. But I use template instead of rendering to existing divs.


Solution

  • Render the parent view, then assign the '.prices' as the el of the child:

    var ParentView = Backbone.View.extend({
        render : function() {
            var html='<h1>Parent View</h1><div class="productInfo"></div><div class="prices"></div><div class="photos"></div>';
            this.$el.html(html);
    
            var prices = new PricesView({
                el : this.$('.prices')
            });
            prices.render();
        }
    });
    
    var PricesView = Backbone.View.extend({
        render : function() {
            var html='<h2>Prices View</h1>';
            this.$el.html(html);
        }
    });
    
    // Create a parent view instance and render it
    var parent = new ParentView({
        el : $('.parent')
    });
    
    parent.render();
    

    Working example on jsfiddle: http://jsfiddle.net/JpeJs/