Skip to content

Instantly share code, notes, and snippets.

@shreyansb
Created January 16, 2012 04:24
Show Gist options
  • Select an option

  • Save shreyansb/1619060 to your computer and use it in GitHub Desktop.

Select an option

Save shreyansb/1619060 to your computer and use it in GitHub Desktop.
intro to backbone: model, collection and view
<html>
<head>
<style>
#color_label {
display: inline-block;
width: 90;
text-align: right
}
#color_bar {
display: inline-block;
width: 1000;
}
</style>
<script src="js/underscore.js"></script>
<script src="js/json2.js"></script>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/backbone.js"></script>
<script src="js/css_colors.js"></script>
<script type="text/javascript">
$(function() {
// Model
Color = Backbone.Model.extend({
validate: function(attributes) {
var color_formatted = attributes.name.toLowerCase();
if (css_colors.indexOf(color_formatted) == -1) {
return color_formatted + ' is not a css color name';
}
},
initialize: function() {
this.bind('error', function(model, error) {
console.log('error: '+ error);
});
},
defaults: {
name: null
}
});
// Collection
Colors = Backbone.Collection.extend({
initialize: function(models, options) {
this.bind('add', options.view.addColor);
}
});
// View
AppView = Backbone.View.extend({
el: $('body'),
events: {
'click #add_color': 'showAddColorPrompt'
},
initialize: function() {
this.colors = new Colors(null, {view: this});
},
showAddColorPrompt: function() {
var color_name = prompt("Add a color");
var color_model = new Color;
if (color_model.set({name: color_name})) {
this.colors.add(color_model);
}
},
addColor: function(model) {
var context = {
color_name: model.get('name')
};
var color_html = _.template($('#color_template').html(), context)
$('#color_list').append(color_html);
}
});
var appview = new AppView();
});
</script>
</head>
<body>
<button id="add_color">Add a color</button>
<div id='color_list'></div>
<script id='color_template' type='text/template'>
<div id='color_label' style='color:<%= color_name %>'><%= color_name %></div>
<div id='color_bar' style='background:<%= color_name %>; color:<%= color_name %>'>.</div>
<div></div>
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment