Simple Inheritance in Backbone.js
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script src="https://getfirebug.com/firebug-lite.js"></script>
<!--
TwitterBootstrap Skeleton
-->
<div class="container">
<header class="page-header">
<h2>BackboneKIT - <small>Inheritance Example</small></h2>
<a href="https://github.com/movableapp/BackboneKit">fork on GitHub</a>
</header>
<section id="app"></section>
<section style="margin-top:20px;padding-top:20px;border-top:1px solid #aaa">
<h3>Fork on GitHub</h3>
<p>
<a href="https://github.com/movableapp/BackboneKit">BackboneKIT is available on GitHub to download and fork! It's free!</a>
</p>
<h3>Follow Me!</h3>
<p>
Don't forget to <b>follow me on Twitter</b>: <a href="https://twitter.com/movableapp" target="_blank">@MovableAPP</a>
</p>
<p>
<a href="https://twitter.com/movableapp" class="twitter-follow-button" data-show-count="false">Follow @movableapp</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</p>
</section>
</div>
JavaScript
/**
* BackboneKIT Inheritance Example
* https://github.com/movableapp/BackboneKit
*
* CAUTION: This example is based on "Lord of the Ring" characters!!!
* Be careful with Saruman!
*/
var Character = Backbone.View.extend({
events:{
'click':'test'
},
initialize: function( opt ) {
_.bindAll(this, 'test');
},
test: function(){
alert("were");
},
getPart: function() {
if ( this.options.part ) return '[' + this.options.part + '] ';
return '';
},
getInfo: function() {
return this.getPart() + this.options.name;
},
render: function() {
this.$el.html( this.getInfo() );
return this.el;
}
});
var GoodCharacter = Character.extend({
initialize: function( opt ) {
_.bindAll(this, 'ha');
// Let create instance with only character's name as string!
if ( _.isString(opt) ) {
opt = { name:opt };
this.options = _.extend( this.options, opt );
}
// Add the rendered view to the page DOM (BackboneKIT utility)
//this.appendTo('#app');
},
ha: function()
{
alert("test");
}
});
/**
* Just create some characters to play with!
*/
p1 = new GoodCharacter('Frodo');
/**
* BackboneBoilerplate jsFiddle - please don't remove this comment!
* http://movableapp.com/2012/06/backbone-boilerplate-jsfiddle/
*/