BB: Inheritance
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css">
<div class="js-ctn"></div>
<script type="text/template" class="js-template">
<button class="js-action--one">Method One</button>
<button class="js-action--two">Method Two</button>
</script>
SCSS
* {
-webkit-font-smoothing: antialiased;
}
body {
padding: 5%;
}
JavaScript
console.clear();
var data = {
date: new Date()
};
// Classes
var Model = Backbone.Model.extend();
var BaseView = Backbone.View.extend({
methodOne: function() {
console.log('Method one has been called');
},
methodTwo: function() {
console.log('Method two has been called');
}
});
var PersonView = BaseView.extend({
events: {
'click .js-action--one': 'methodOne',
'click .js-action--two': 'methodTwo'
},
template: _.template( $('.js-template').html() ),
render: function() {
this.$el.html( this.template( this.model.attributes ) );
return this;
},
// if I need to do something
methodOne: function() {
console.log('Updated methodOne');
// http://makandracards.com/makandra/22121-how-to-call-overwritten-methods-of-parent-classes-in-backbone-js
this.constructor.__super__.methodOne.apply(this, arguments);
//or
//BaseView.prototype.methodOne.apply(this, arguments);
}
});
// Setup
var personView = new PersonView({
model: new Model(data, {parse:true})
});
// Add to DOM
$('.js-ctn').html(personView.render().el);