1

このビューに間隔があります

var QuestionsView = Backbone.View.extend({
    render: function(){
        var view = this;
        this.updateQuestionsIntervalId = setInterval(function() {view.refreshQuestionLists()}, 3000);
    ),

    refreshQuestionLists: function() {
        this.questions.fetch({ 
            ...
        });
    },

    navigateAway: function() {
        clearInterval(this.updateQuestionsIntervalId);
    }

}); 

QuestionView.navigateAway()理想的にはルートが変わったら走りたいです。とにかく私はこれを行うことができますか?

ありがとう

4

2 に答える 2

1

手間のかからない解決策として、viewメソッドをイベントに直接バインドできます。router:routeイベントは、ルーターが定義されたルートへのURL変更を照合するたびに発生します。

var QuestionsView = Backbone.View.extend({
  initialize: function(){
    this.listenTo(yourRouter, 'route', this.navigateAway); 
  )
}); 

これはうまくいくはずですが、私にはスパゲッティのように感じます。

私は通常onBeforeClose、ビューにメソッドを実装しました。このメソッドは、現在のビューから移動する前に呼び出します。次のようになります:

var Router = Backbone.Router.extend({
  navigateToView: function(view) {
    //I've actually abstracted this logic to a separate
    //view manager class, but you get the idea...
    var current = this.currentView; 
    if(current) {
      if(current.onBeforeClose)
        current.onBeforeClose();
      current.remove();
    }

    this.currentView = view;
    //render your current view here, however you like
    $(body).html(this.currentView.render().el);
  },

  someRoute: function() {
    var view = new SomeView();
    this.navigateToView(view);
  }
});

それは何よりも慣習です。ビューにメソッドがない場合、そのビューはonBeforeClose呼び出されず、害はありません。

これには、1つの集中化された方法(この場合)を使用してビューをレンダリングする必要があることに注意してください。ただし、関係なくnavigateToViewを使用して古いビューをクリーンアップする必要があるため、これは良いことですremove

于 2013-02-05T12:18:21.840 に答える
0

これを行う必要がある理由は、前の間隔を停止してビューがレンダリングされたときに開始する複数の間隔を停止するためでした。

しかし、私は少なくとも1つの実行が必要です...

だから私は間違った道をたどりました、解決策:

var QuestionsView = Backbone.View.extend({

    updateQuestionsIntervalId: false,

    render: function(){
        var view = this;

        if(this.updateQuestionsIntervalId == false)
            this.updateQuestionsIntervalId = setInterval(function() {view.refreshQuestionLists()}, 3000);
    ),

    refreshQuestionLists: function() {
        this.questions.fetch({ 
            ...
        });
    }

}); 
于 2013-02-05T12:40:21.100 に答える