Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu
Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government
Rewrite the application with the help of Backbone components!
Use a package manager for client side dependencies! (bower)
bower
.bowerrc
settingsbower init
bower install --save bootstrap jquery underscore
bower install --save backbone
index.html
var CodeSnippet = Backbone.Model.extend({
defaults: function() {
return {
title: '',
code: '',
type: 'js',
};
},
});
//Usage
console.log(new CodeSnippet());
var CodeSnippetCollection = Backbone.Collection.extend({
model: CodeSnippet,
getTitles: function(filterText = '') {
return this.snippets
.map(sn => sn.title)
.filter(t => t.indexOf(filterText) > -1);
}
});
//Usage
console.log(new CodeSnippetCollection(snippets));
Naive solution
var ListView = Backbone.View.extend({
initialize(props) {
props = props || {};
this.list = props.snippets;
this.template = _.template( $('#listItems').html() );
$('#text-filter').on('keyup', this.onKeyUp.bind(this));
},
onKeyUp(e) {
var filterText = e.currentTarget.value;
var filteredTitles = this.list.getTitles(filterText);
$('#code-list').html(this.template({
coll:filteredTitles
}));
}
});
Using specific Backbone features
var ListView = Backbone.View.extend({
el: '#list-container',
template: _.template( $('#listItems').html() ),
filterText: '',
events: {
'keyup #text-filter': 'onKeyUp'
},
initialize: function() {
// this.render();
},
render: function () {
this.$('#code-list').html( this.template( {
coll: this.collection.getTitles(this.filterText)
}));
},
onKeyUp: function (e) {
this.filterText = e.currentTarget.value;
this.render();
}
});
new ListView({
collection: new CodeSnippetCollection(snippets)
});
serializeData()
ensures an intermediate layer between the model and the view
var ListView = Backbone.View.extend({
render: function () {
this.$('#code-list').html( this.template( this.serializeData(this.collection) ) );
},
serializeData: function (coll) {
return {
coll: coll.getTitles(this.filterText)
};
}
});