1

Here is a sample page I set up, in which a #blueSquare div is made visible after the backbone view has been rendered. Even though the code is placed before the creation of the view. I would expect to see the blue square to show instantly and not after the (forcibly long) rendering of the view. My aim is to make a loading spinner to show before the view is created, and hides after the view is rendered. But I don't understand this problem.

<style>

#blueSquare
{
    position: absolute;
    top: 100px;
    left: 100px;
    width: 100px;
    height: 100px;
    background: blue;
    display: none;
}

</style>

<script type="text/javascript" src="js/ext/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/ext/underscore-min.js"></script>
<script type="text/javascript" src="js/ext/backbone-min.js"></script>
<script type="text/javascript">

$(document).ready(function(){

    TestView = Backbone.View.extend(
    {
        initialize: function()
        {
            console.log('initialize view');
            for (var i = 0; i < 1000000000; i++)
            {
                var t = Math.sqrt( i );
            }
            this.render();
        },
        render: function()
        {

            console.log('render view');
            //$('#blueSquare').hide();
        }
    });

    $('#blueSquare').show();
    var testView = new TestView();

});

</script>

<div id="blueSquare"></div>

1 Answers1

3

The easiest solution is to defer the creation of the view to allow the DOM to refresh. You can do this by wrapping the view creation in a _.defer()

$('#blueSquare').show();
_.defer(function(){
    var testView = new TestView();
});

As for the explanation of why, see Why is setTimeout(fn, 0) sometimes useful?

Community
  • 1
  • 1
Cubed Eye
  • 5,581
  • 4
  • 48
  • 64
  • Thank you! I got it working in the end. Although the underscore defer function broke my backbone code, the setTimeout alternative worked fine. – Jan Robert Leegte Mar 17 '14 at 13:01