JavaScript technologies

Rewriting the example with Backbone

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

Task

Rewrite the application with the help of Backbone components!

Use a package manager for client side dependencies! (bower)

Installation

  1. Install bower
  2. .bowerrc settings
  3. bower init
  4. bower install --save bootstrap jquery underscore
  5. bower install --save backbone
  6. Set up script references in index.html

Models

var CodeSnippet = Backbone.Model.extend({
    defaults: function() {
        return {
            title: '',
            code: '',
            type: 'js',
        };
    },
});
//Usage
console.log(new CodeSnippet());

Collections

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));

Views

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 
        }));
    }
});

Views

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();
    }
});

Starting the application

new ListView({
    collection: new CodeSnippetCollection(snippets)
});

Introducing the "ViewModel"

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)
        };
    }
});