Skip to content

Instantly share code, notes, and snippets.

@gautamarora
Last active August 29, 2015 14:18
Show Gist options
  • Save gautamarora/6f98b5473e0862cadb0d to your computer and use it in GitHub Desktop.
Save gautamarora/6f98b5473e0862cadb0d to your computer and use it in GitHub Desktop.
Learning Backbone
var todo = new Todo({text:"learning backbone"}); //creates new todo
todo.toJSON() //logs todo as json object
JSON.stringify(todo) //logs todo as json string
todo.get("text") //get value of attribute
todo.set({done: true}) //set value of attribute. note: this fires 'todo:change:done' & 'todo:change'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Backbone</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<script>
var Todo = Backbone.Model.extend({
defaults: {
text: '',
done: false
},
validate: function(attrs) {
console.log("Todo:validate");
},
initialize: function() {
console.log("Todo:init");
this.on('change', function() {
console.log('Todo:change');
})
this.on('change:done', function() {
console.log('Todo:change:done');
})
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment