Question

I'm working on converting a single-page app to backbone.JS. The View below uses the body tag as it's tagName - ie, I want the view to occupy the entire content of the page. I don't want to use container divs or other hacks.

var ThingView = Backbone.View.extend({  
    tagName : "body",
            ... 


    // Show the HTML for the view 
    render : function() {  
        console.log('Displaying thing')
        $(this.el).append('<h1>test</h1>');
        console.log('finished')
        console.log($(this.el))
        return this; // For chaining

When rendering, I see

finished
[
<body>​
    <h1>​test​</h1>​
</body>​
]       

But after I inspect the DOM, the body no longer has the text.

Was it helpful?

Solution

tagName indicates what tag Backbone should use to create its el if no el is provided by the constructor. The created element is not automatically inserted into the DOM.

The simplest way is probably to create your view with its el set to body :

new ThingView({el:'body'})

OTHER TIPS

What nikoshr explained is correct. Adding to it, Using tagName is correct. but Ideally you should use el element, which is defined in Backbone.js library as an element (el) of View.

Below is the ideal code you should use while doing this.

<script type="text/javascript">
            $(document).ready(function(){  
             var ThingView  = Backbone.View.extend({
                    el:$("body"),                   
                    initialize: function(){
                            _.bindAll(this,"render");
                            this.render();  
                    },
                    render:function(){
                        this.el.append('<h1>test</h1>');    
                        console.log('finished');
                        console.log($(this.el).html());                     
                    }
                });    
                var ThingView = new ThingView();
            });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top