mikemaccana
mikemaccana

Reputation: 123108

Backbone.JS view renders, but not displayed on page

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.

Upvotes: 1

Views: 2146

Answers (2)

Umesh Patil
Umesh Patil

Reputation: 10685

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>

Upvotes: 0

nikoshr
nikoshr

Reputation: 33344

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'})

Upvotes: 7

Related Questions