Last active
December 8, 2016 22:19
-
-
Save dengjonathan/f65494dc61074d49932da34ab58e83df to your computer and use it in GitHub Desktop.
Vanilla MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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