0

I am using backbone to create all my views. Some of my views are quite resource intensive and take a while to load into the template. So when clicking on some line, I want to first show a loading overlay and remove it when the view is rendered.

$('.class').live('click', function(){
    $("#loading").fadeIn(); 
    // this changes the url and then the view is called.
});

But the problem is that the loading but only comes up once the view is rendered. Why is this? what is the event pattern here? Like when you click on the link does it load the url first then only the things inside the click callback, cause it seems so. Even with this it does the same:

$('.content a').click(function () {
     var f = $(this);
     $("#loading").show();
     Backbone.history.navigate(f.attr("href"), true);
     return false;
 });
4

1 回答 1

0

这是可能的事件顺序:

  1. 点击发生。
  2. $("#loading").fadeIn();叫做。
  3. 您更改 URL 并激活路由器。
  4. 您的视图已激活并开始渲染。
  5. 您的视图完成渲染。
  6. 浏览器再次获得控制权并开始清除工作积压,特别是浏览器最终到达fadeInfrom 1

例如,看看像这样简单的东西做了什么:

$('button').click(function() {
    $('div').after('<p>Loading...</p>');
    for(var i = 0; i < 10000; ++i)
        $('div').text(i);
});​

演示:http: //jsfiddle.net/ambiguous/sEvv5/

您可能需要根据计算机的速度向上或向下调整 10000。

您需要做的是在您放置#loading和开始渲染昂贵视图之间将控制权交还给浏览器。一种常见的方法是使用setTimeout超时为零;例如:

$('button').click(function() {
    $('div').after('<p>Loading...</p>');
    setTimeout(function() {
        for(var i = 0; i < 10000; ++i)
            $('div').text(i);
    }, 0);
});​

演示:http: //jsfiddle.net/ambiguous/qd9Ly/

在您的情况下,请尝试将// this changes the url and then the view is called.零件放入setTimeout.

于 2012-05-04T15:50:47.300 回答