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 に答える