backbone reusable view test
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<div id="myView">uninitialized view</div>
<input id="input" value="10" name="count" type="text" size="5" maxlength="10" />
<a href="#" onclick="generateModels();" >create models</a>
JavaScript
/*
clean up view after setting new model
*/
Model = Backbone.Model.extend({
defaults: {
id:1,
blah:'blubb',
foo:'bar'
},
click: function() {
console.log('model id ' + this.get('id') + ' clicked');
},
mouseOver: function() {
console.log('model id ' + this.get('id') + ' mouse over');
}
});
ReusableView = Backbone.View.extend({
el: "#myView",
events: {
"click": "onClicked",
"mouseover": "onMouseOver"
},
initialize: function() {
if ( !this.template) {
this.template = _.template('<h1>Model <%= id %></h1>');
}
this.listenTo( model, 'change', this.onChange);
this.render();
},
render: function() {
this.$el.html( this.template( this.model.attributes));
},
onClicked: function() {
console.log('view of model id ' + this.model.get('id') + ' clicked');
this.model.click();
},
onMouseOver: function() {
console.log('view model id ' + this.model.get('id') + ' mouse over');
this.model.mouseOver();
},
onChange: function() {
console.log( 'model ' + this.model.get('id') + ' changed');
},
setModel: function( model) {
// unbind all view related things
this.$el.children().removeData().unbind();
this.$el.children().remove();
this.stopListening();
// clear model
if ( this.model) {
this.model.unbind();
this.model.stopListening();
}
// set new model and call initialize
this.model = model;
this.delegateEvents( this.events); // will call undelegateEvents internally
this.initialize();
}
});
var model = new Model();
var view = new ReusableView({model:model});
generateModels = function() {
//console.log( $('#input').val());
var count = parseInt( $('#input').val());
for(var i=0;i<=count;i++) {
...