问题描述:

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

}

});

The above one is sample of my code. Whenever router renders a view, it will unbind all the events attached to the existing view so that it will dispose, and create a new view. Since I have attached onResize event with window, for each instance of someView (navigate from #something to #anotherthing and come back to #something, this will unbind all events in existing this.someView, and create a new this.someView instance), it will bind an event to the window, and the onResize method getting triggered multiple times, even though the current view is not in the display (i.e. my router might display some other views which is defined in method2). I understand why its getting triggered multiple times, but want to know is there anyway to handle this in backbone or in jQuery instead of bind events to the window's resize event?

P.S. I am not using jQuery.mobile, and don't want to use any extra javascript plugins since it will increase the mobile browser load.

网友答案:

Just add Jquery unbind (off) to window resize upon close function:

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();
 }
相关阅读:
Top