jquerybackbone.jsbackbone-viewsbackbone-eventsdocument-ready

How to render Backbone.js view AFTER jQuery document ready has fired?


I have a simple Backbone.js page where in the view I am getting a div from the DOM and adding another div to it....

<body>
<div id="starbase"></div>
<script type="text/javascript">
(function($){

    var ListView = Backbone.View.extend({
        el: $("#starbase"), 

        initialize: function(){
            _.bindAll(this, 'render'); 
            this.render(); 
        },
        render: function(){
            $(this.el).append('<div id="starship"></div>');
        }
    });

    var listView = new ListView();
})(jQuery);
</script>
</body>

Is there any way I can force this render function to fire after jQuery DOM ready event has happened? Meaning the starship div should only get added to the starbase div after the jQuery ready has already happened.


Solution

  • Just add on the ready event the constructor call. See the example below:

    (function($){
    
    var ListView = Backbone.View.extend({
        el: $("#starbase"), 
    
        initialize: function(){
            _.bindAll(this, 'render'); 
            this.render(); 
        },
        render: function(){
            $(this.el).append('<div id="starship"></div>');
        }
    });
    
     $( document ).ready(function() {
        var listView = new ListView();
    });
    })(jQuery);