Search code examples
javascriptbackbone.js

Backbone code not rendering simple View


Simple backbone View is not rendering inside of the element, and there are no errors

<html>
    <head>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.9/backbone-min.js"></script>
    </head>

    <body>
        <script type="text/javascript">
            var SearchView = Backbone.View.extend({
                el: '.container',
                initialize: function() {
                    this.render();
                },
                render: function() {
                    $(this.el).html("hello"); //tried both but not working. 
                    this.$el.html("hello"); 
                } 
             }); 
             var search_view = new SearchView();
        </script>
        <div class="container"></div>
    </body>
</html>

Solution

  • Your problem is because you're not waiting for the DOM to be ready, try moving the div like this (http://jsfiddle.net/icodeforlove/68gGS/)

    <body>
        <div class="container"></div>
        <script type="text/javascript">
            var SearchView = Backbone.View.extend({
                el: '.container',
                initialize: function() {
                    this.render();
                },
                render: function() {
                    $(this.el).html("hello"); //tried both but not working. 
                    this.$el.html("hello"); 
                } 
             }); 
             var search_view = new SearchView();
        </script>
    </body>