Backbone.js listenTo window resize throwing [object Object] has no method 'apply' error

Zengineer picture Zengineer · Jan 22, 2013 · Viewed 11.6k times · Source

Problem:

I'm trying to attach a resize event to the window from a view using the new listenTo() method in Backbone.js. The event seems to bind to the window, however, when the window is actually resied the following error is thrown:

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

Here is the code that attaches the event to the view:

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

Here is the resizeContext function:

  resizeContext: function(event) {

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

            this.setHeight();

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

        }

Note: using the standard $(window).on("resize",this.resizeContext) attaches the event and runs as it should. I am trying to take advantage of the new stopListening() feature that is added to view.remove();

Answer

jevakallio picture jevakallio · Jan 22, 2013

The new listenTo and stopListening are methods of the Backbone.Events mixin, and they can only be used to listen to Backbone events which are triggered with .trigger, such as the built-in collection:add, or model:change events.

That means that you won't be able to utilize the stopListening functionality for DOM events such as window:resize.

Consider overriding the View.removemethod instead.

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);
  }
});