Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  112] [ 4]  / answers: 1 / hits: 17109  / 13 Years ago, thu, february 2, 2012, 12:00:00

I have been trying to attach a handler to the resize event in one of my Backbone views. After doing some research I have discovered that you can only attach events to the view's element or its descendants.


This is an issue for me because the visual effect I am trying to achieve is not possible using pure CSS and requires some JS to set the dimensions of the content area element based on the window minus the header element.


If you are having trouble visualizing what I am trying to do, imagine a thin header and a content area which must occupy the remaining space with no CSS background trickery.


define(
[
'jQuery',
'Underscore',
'Backbone',
'Mustache',
'text!src/common/resource/html/base.html'
],
function ($, _, Backbone, Mustache, baseTemplate) {
var BaseView = Backbone.View.extend({

el: $('body'),

events: {
'resize window': 'resize'
},

render: function () {
var data = {};

var render = Mustache.render(baseTemplate, data);

this.$el.html(render);

this.resize();
},

resize: function () {
var windowHeight = $(window).height();

var headerHeight = this.$el.find('#header').height();

this.$el.find('#application').height( windowHeight - headerHeight );
}
});

return new BaseView;
}
);

More From » backbone.js

 Answers
116
var BaseView = Backbone.View.extend({

el: $('body'),

initialize: function() {
// bind to the namespaced (for easier unbinding) event
// in jQuery 1.7+ use .on(...)
$(window).bind(resize.app, _.bind(this.resize, this));
},

remove: function() {
// unbind the namespaced event (to prevent accidentally unbinding some
// other resize events from other code in your app
// in jQuery 1.7+ use .off(...)
$(window).unbind(resize.app);

// don't forget to call the original remove() function
Backbone.View.prototype.remove.call(this);
// could also be written as:
// this.constructor.__super__.remove.call(this);
}, ...


Don't forget to call the remove() function on the view. Never just replace the view with another one.


[#87679] Tuesday, January 31, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisa

Total Points: 514
Total Questions: 93
Total Answers: 93

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;