Backbone.js - Models, Views
COMMAND AND CONTROL (and conquer)
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<ul id="container"></ul>
JavaScript
var Lead = Backbone.Model.extend({
defaults: {
first_name: '',
last_name: '',
email_address: '[email protected]',
subscribe_newsletter: true,
},
initialize: function(options) {
console.log('initialize, options passed: ', options);
},
render: function() {
console.log('render')
},
parse: function() {
console.log('parse')
},
validate: function(attrs) {
console.log('validate', attrs)
}
});
var lead = new Lead({ first_name: 'steve', last_name: 'senkus'})
console.log(lead)
lead.on('change', function(e) {
console.log('model changed')
})
lead.set({
first_name: 'fillip',
email_address: '[email protected]'
}, {validate: true})
var TodoView = Backbone.View.extend({
tagName: 'li',
// Cache the template function for a single item.
todoTpl: _.template( "An example template" ),
events: {
'dblclick label': 'edit',
'keypress .edit': 'updateOnEnter',
'blur .edit': 'close'
},
initialize: function() {
this.render();
},
// Re-render the title of the todo item.
render: function() {
this.$el.html( this.todoTpl( 'asdfadsfa'));
this.input = this.$('.edit');
return this;
},
edit: function() {
// executed when todo label is double clicked
},
close: function() {
// executed when todo loses focus
},
updateOnEnter: function( e ) {
// executed on each keypress when in todo edit mode,
// but we'll wait for enter to get in action
}
});
var todoView = new TodoView();
// log reference to a DOM element that corresponds to the view instance
$('#container').append(todoView.$el); // logs <li></li>