Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Last active December 8, 2016 22:19
Show Gist options
  • Save dengjonathan/f65494dc61074d49932da34ab58e83df to your computer and use it in GitHub Desktop.
Save dengjonathan/f65494dc61074d49932da34ab58e83df to your computer and use it in GitHub Desktop.
Vanilla MVC
<!DOCTYPE html>
<html>
<head>
<title>Backbone.js MVC</title>
</head>
<body>
<div id="app"></div>
<!-- App Dependencies -->
<script
src="https://code.jquery.com/jquery-3.1.1.slim.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.3.3/backbone-min.js"></script>
<script>
const app = {};
$(function() {
// MODEL: where we store all the data
const Counter = Backbone.Model.extend({
initialize: function() {this.set('value', 0)},
increment: function() {this.set('value', this.get('value') + 1)},
decrement: function() {this.set('value', this.get('value') - 1)}
});
// VIEW: DOM nodes representing what is displayed on page
// CONTROLLER: Backbone includes user events in View.events
const CounterView = Backbone.View.extend({
tag: 'article',
template: _.template(`<div class="counter">
<button id="up">+</button>
<p id="count">
<%= value %>
</p>
<button id="down">-</button>
</div>`),
events: {
'click #up': function() {this.model.increment()},
'click #down': function() {this.model.decrement()}
},
initialize: function() {
this.model.on('change:value', function() {
this.render();
}, this);
},
render: function() {
return this.$el.html(this.template(this.model.attributes));
}
});
// INIT
app.counter = new Counter();
app.counterView = new CounterView({model: app.counter});
$('#app').append(app.counterView.render());
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment