A Backbone.View represents a logical chunk of UI. It manages a DOM element (this.el) and handles events via delegation.
Core Lifecycle Methods:
preinitialize(options): Runs before any instantiation logic. Use this for setup that must happen before this.el is created.initialize(options): The standard initialization method. Override this for your view's logic.render(): The core method to populate this.el with HTML. Convention: Always return this to allow chaining.remove(): Removes the view's element from the DOM and stops all event listeners.
Event Delegation:
Define an events hash to map DOM events to view methods:
events: {
'click .button': 'handleClick',
'mousedown .title': function(e) { ... }
}
Key Properties:
this.el: The root DOM element of the view.this.$el: The jQuery-wrapped version of this.el.this.cid: A unique ID for the view instance.
var MyView = Backbone.View.extend({
el: '<div>',
events: {
'click .btn': 'onBtnClick'
},
initialize: function() {
console.log('View initialized');
},
render: function() {
this.$el.html('<button class="btn">Click Me</button>');
return this;
},
onBtnClick: function() {
alert('Button clicked!');
}
});
const view = new MyView();
view.render().$el.appendTo('body');