Destroying a Backbone View
Destroying a Backbone View
HTML
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<p id="instr">Click Me</p>
<div id="rootEl" class="red"></div>
<button id="butt">destroy()</div>
CSS
#rootEl {
height:150px;
width:150px;
}
.red {
background-color:red;
}
.blue {
background-color:blue;
}
.green {
background-color:green;
}
.yellow {
background-color:yellow;
}
.black {
background-color:black;
}
.square {
float:left;
height:50px;
width:50px;
}
JavaScript
var CoolView = Backbone.View.extend({
el: $("#rootEl"),
initialize: function () {
this.colors = this.model.get('colors');
console.log('thingy');
},
events: {
'click': 'clickHandler',
'touchend': 'clickHandler'
},
destroy: function () {
//unbind delegated events above.
this.undelegateEvents();
//remove data and unbind jQuery events
this.$el.removeData().unbind();
//empty child elements from el
this.$el.remove();
$('#instr').text('Child elements and click listeners are GONE');
},
clickHandler: function (evt) {
var color = this.getColor();
var newSquare = '<div class="square ' + color + '">';
$(this.el).append($(newSquare));
this.render();
console.log('clicked ' + evt.currentTarget.id);
console.log('new color ' + color);
},
index: 0,
getColor: function () {
var ret = this.colors[this.index];
if (this.index < this.colors.length - 1) {
this.index++;
} else {
this.index = 0;
}
return ret;
}
});
var CoolModel = Backbone.Model.extend({
defaults: {
colors: ['blue', 'green', 'yellow', 'black']
}
});
var view = new CoolView({
model: new CoolModel({})
});
$('#butt').click(function () {
view.destroy();
});