20

問題:

Backbone.jsの新しいlistenTo()メソッドを使用して、ビューからウィンドウにサイズ変更イベントをアタッチしようとしています。イベントはウィンドウにバインドされているように見えますが、ウィンドウが実際に再利用されると、次のエラーがスローされます。

Uncaught TypeError:Object [object Object] has no method'apply' jquery.js:2 p.event.dispatch jquery.js:2 p.event.add.g.handle.h

イベントをビューに添付するコードは次のとおりです。

this.listenTo($(window),"resize", this.resizeContext, this));

これがresizeContext関数です。

  resizeContext: function(event) {

            console.log("resizing context for "+this.id);

            this.setHeight();

            // trigger resize event (use event bus)
            this.options.vent.trigger("resize", event);

        }

注:標準を使用する$(window).on("resize",this.resizeContext)と、イベントが添付され、正常に実行されます。stopListening()に追加された新機能を利用しようとしていますview.remove();

4

3 に答える 3

33

新しいlistenTostopListeningBackbone.Eventsmixinのメソッドであり.trigger、組み込みのcollection:addmodel:changeイベントなどの でトリガーされるバックボーン イベントをリッスンするためにのみ使用できます。

つまり、stopListeningなどの DOM イベントの機能を利用できなくなりますwindow:resize

View.remove代わりにメソッドをオーバーライドすることを検討してください。

var SomeView = Backbone.View.extend({
  initialize:function() {
    $(window).on("resize",this.resizeContext)
  },

  remove: function() {
    $(window).off("resize",this.resizeContext);
    //call the superclass remove method
    Backbone.View.prototype.remove.apply(this, arguments);
  }
});
于 2013-01-22T14:47:52.557 に答える
1

私のコードでは、 .debounce( (this.resizeContext).bind(this)) を実行する必要があります。

これにより、オフになりにくくなります。汚い解決策として、ビューを削除するときにすべての「サイズ変更」リスナーをオフにします。新しいビューでは、サイズ変更リスナーがあれば、再びオンになると思います。

remove: function() {
    $(window).off("resize");
    //call the superclass remove method
    Backbone.View.prototype.remove.apply(this, arguments);
}
于 2014-05-15T01:01:47.063 に答える