0

すみません、タイトルが少しわかりにくいです。

バックボーン ルーターの構造は次のとおりです。

var AppRouter = Backbone.Router.extend({
    routes: {
      'notes': 'showNotes',
      'news': 'showNews'
    },
    showNews: function() {
        // make view object and render
    },
    showNotes: function() {
        // make view object and render
    },
    initialize: function() {
        this.user.fetch({success: function(){
            // callback function
        }});
    }
});

私が抱えている問題は、ユーザーをビューに渡す必要があるため、成功コールバックが初期化内で実行される場合にのみ各レンダリングを実行する必要があることです。基本的に、コールバックが呼び出されるまで初期化を終了させたくありません。どうすればこれを達成できるかわかりません。

ありがとう

4

1 に答える 1

2

Router#initializeは、デフォルトでは空の関数です。それが実行された時点で、ルートはすでに に渡されておりHistory、おそらくそれらを防ぐための「クリーンな」方法を通り過ぎています。

ルーターがレンダリングを開始する前にユーザーを確実に取得する必要がある場合は、次のように、履歴が始まる前に取得することで実現できますuser

  // in some initializer:
  user.fetch({success: function() {
    var router = new AppRouter({user: user});
    Backbone.history.start();
  }});

  // and your router:
  initialize: function(options) {
    if (options) this.user = options.user;
  }

ただし、ビューが事前にロードされていることを確認するのではなく、フェッチされているユーザーにビューを応答させることも理にかなっている場合があります。ビューは、ユーザーがロードするまで何もレンダリングしないか、「ロード中」のグラフィックなどを表示する場合があります。その場合は、次のようにします。

// in your router
showNotes: function() {
  // note sure how you're storing your views, but for example:
  this.currentView = new ShowNotesView({model: this.user}).render();
},

initialize: function() {
  this.user.fetch();
}

// and in the view
initialize: function() {
  this.model.on('sync', this.render.bind(this));
},

render: function() {
  // note that `hasBeenSynced` is a made up property.  Fill it in with something
  // that indicates the model has been fetched successfully.  Alternatively you
  // might do this in the template.  Lot of flexibility here.
  if (this.model.hasBeenSynced) {
    // render the model
  } else {
    // show nothing, a loading template, etc
  }
  return this;
}
于 2013-01-19T22:50:29.687 に答える