Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created April 25, 2012 20:13
Show Gist options
  • Select an option

  • Save simenbrekken/2492985 to your computer and use it in GitHub Desktop.

Select an option

Save simenbrekken/2492985 to your computer and use it in GitHub Desktop.
Simple Backbone MVC
<!doctype html>
<html>
<head>
<title>Backbone Routing Example</title>
<meta charset="utf-8">
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/projects">Projects</a>
<a href="/about">About</a>
</nav>
<div class="output"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
var View = Backbone.View.extend({
events: {
'click nav a': 'linkClick'
},
initialize: function() {
this.model.on('change:content', this.contentChange, this);
},
linkClick: function(e) {
e.preventDefault();
var url = $(e.target).attr('href');
Backbone.history.navigate(url, true);
},
contentChange: function(model, content) {
this.$('.output').html(content);
}
})
var Router = Backbone.Router.extend({
routes: {
'': 'showHome',
'projects': 'showProjects',
'about': 'showAbout'
},
initialize: function() {
this.model = new Backbone.Model();
this.view = new View({
el: $('body'),
model: this.model
});
},
showHome: function() {
this.model.set('content', 'Home!');
},
showProjects: function() {
this.model.set('content', 'Projects!');
},
showAbout: function() {
this.model.set('content', '<iframe src="http://player.vimeo.com/video/37280197" width="400" height="300" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>');
}
});
var router = new Router();
$(function () {
Backbone.history.start({});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment