Skip to content

Instantly share code, notes, and snippets.

@christophervigliotti
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophervigliotti/452a9905ddf6d6398e51 to your computer and use it in GitHub Desktop.
Save christophervigliotti/452a9905ddf6d6398e51 to your computer and use it in GitHub Desktop.
Checking Out Backbone.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<ul id="theul"><li>sweet child of theul</li></ul>
<div id="thediv">thediv</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<script>
// is the library loaded?
console.log(Backbone);
// MODEL
// define the model
var WorldGreeter = Backbone.Model.extend({
// properties
defaults: {
name: 'J. S. Mc Backbone',
age: 23,
message: 'Hello World'
},
//
validate: function(attributes){
if ( attributes.age < 0){
return 'not born yet';
}
if ( !attributes.name ){
return 'string needs food badly';
}
}
});
// instance
var worldGreeter = new WorldGreeter();
// getting and setting
console.log(worldGreeter.get('message'));
worldGreeter.set('message','hallå världen');
console.log(worldGreeter.get('message'));
// another instance
var fancyWorldGreeter = new WorldGreeter({name:'Twenty Two Bugbears',age:77,message:'Hullo Woyld'});
// this will not set the var to -1...
worldGreeter.set('age',-1,{validate: true}); // the third arg is new(er than the tutorial that I am currently scraping)
// ... but this will ...
fancyWorldGreeter.set('age',-1);
console.log(worldGreeter.get('age'));
console.log(fancyWorldGreeter.get('age'));
// VIEW
// defining the view...
var WorldGreeterView = Backbone.View.extend({
tagName: 'li',
initialize: function(){
this.render();
},
render: function(){
var renderString = 'My name is ' + this.model.get('name') + ', I am ' + this.model.get('age') + ' earth years old and I am programmed to say "' + this.model.get('message') + '". Pew pew.';
console.log(renderString);
this.$el.html(renderString);
}
});
// new view instance
var worldGreeterView = new WorldGreeterView({ model: worldGreeter });
$('#theul').append(worldGreeterView.el);
console.log(worldGreeterView.el);
// resume at http://www.codebeerstartups.com/2012/12/5-explaining-views-in-backbone-js-learning-backbone-js/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment