Backbone 101: Model Methods
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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage-min.js"></script>
<h2 class="pg-heading">Model methods</h2>
<p>This example simply toggles the watchlist boolean by directly referencing toggleWatchlist from the model.</p>
<h3>Output</h3>
<pre class="js-logs"></pre>
CSS
@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);
* {
-webkit-font-smoothing: antialiased;
box-sizing: border-box;
}
body {
font-family: Roboto;
padding: 16px;
line-height: 1.5;
font-weight: normal;
color: #ccc;
background: #292929;
font-size: 18px;
}
h1, h2, h3 {
font-weight: normal;
}
.pg-heading {
margin-bottom: 0;
}
a {
color: #95baf6;
transition: opacity .3s;
}
a:hover {
opacity: 0.75;
}
input {
border: none;
height: 40px;
outline: none;
padding: 0 8px;
}
input[type=submit] {
padding: 0 16px;
background: #2196F3;
color: white;
transition: background .3s;
}
input[type=submit]:hover {
background: #1E88E5;
}
input[type=submit]:active {
background: #1976D2;
}
input[type=text] {
transition: border-color .3s;
border: 1px solid white;
}
input.error {
border: 1px solid #F44336;
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.428571429;
color: #333;
word-break: break-all;
word-wrap: break-word;
background-color: #f5f5f5;
border: 1px solid #ccc;
border-radius: 4px;
}
JavaScript
console.clear();
// Set up contact model
var Movie = Backbone.Model.extend({
defaults: {
watchlist: false,
rated: false
},
toggleWatchlist: function() {
return this.set('watchlist', !this.get('watchlist'));
}
});
// Create some instances
var movie = new Movie();
$('.js-logs').append('1) Movie watchlist = '+movie.get('watchlist')).append('<br>');
// Run model.toggleWatchlist
movie.toggleWatchlist();
$('.js-logs').append('2) Movie watchlist = '+movie.get('watchlist'));