1
var MyRouter = Backbone.Router.extend({
   router : {
         'something'    : 'method1',
         'anotherthing' : 'method2'

   },

   method1 : function () {
         if (!this.someView)
               this.someView.close()

         this.someView = new SomeView();
         $('someElement').append(this.someView.render().el);
   },

   method2 : function() {
     //do something
  }

});

var SomeView= Backbone.View.extend({

    initialize : function() {
        $(window).on('resize',_bind(this.onResize, this));
    },

    onResize : function() {
        alert('resized');
    },

     close : function() {
         this.remove();
         this.off();
         this.undelegateEvents();
     }

});

上記は私のコードのサンプルです。ルーターがビューをレンダリングするときはいつでも、既存のビューに関連付けられているすべてのイベントをバインド解除して、破棄し、新しいビューを作成します。onResize イベントを window にアタッチしたので、someView の各インスタンスに対して (#something から #anotherthing に移動し、#something に戻ると、既存の this.someView 内のすべてのイベントのバインドが解除され、新しい this.someView インスタンスが作成されます)、現在のビューが表示されていなくても、イベントをウィンドウにバインドし、onResize メソッドが複数回トリガーされます (つまり、私のルーターは、method2 で定義されている他のビューを表示する可能性があります)。複数回トリガーされる理由は理解していますが、イベントをウィンドウのサイズ変更イベントにバインドする代わりに、バックボーンまたは jQuery でこれを処理する方法があることを知りたいですか?

PS私はjQuery.mobileを使用していません.モバイルブラウザの負荷が増加するため、余分なjavascriptプラグインを使用したくありません.

4

1 に答える 1

0

Jquery unbind (off) を window resize on close 関数に追加するだけです:

initialize : function() {
    _.bindAll(this, "onResize");// revent the need to use _.bind
    $(window).on('resize',this.onResize);
},   
close : function() {
     $(window).off('resize', this.onResize);
     this.remove();
     this.off();
     this.undelegateEvents();
 }
于 2013-12-22T16:17:57.853 に答える