JavaScript technologies

Application abstraction 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

Backbone

Application abstraction

Basic concepts

Provides an abstract layer around the model and the view.

  • Model: abstraction of the object literal
  • Collection: abstraction of the array literal
  • View: abstraction of the UI logic

Further functionality

  • Events: Observable pattern
    • on()
    • off()
    • trigger()
  • Router: location abstraction

Dependencies

References

Backbone.Model

Declaring, instantiating, using

var Book = Backbone.Model.extend({});

var book1 = new Book({
    title: 'JavaScript Patterns',
    author: 'Stoyan Stefanov'
});

console.log(book1.get('title') === 'JavaScript Patterns');

book1.on('change:title', function (obj) {
    console.log('A könyv címe megváltozott: ', obj)
});
book1.set('title', 'JavaScript Patternity');

Default values

var Book = Backbone.Model.extend({
    defaults: {
        title: 'Generic book title',
        author: 'Anonymous'
    }
});

var book1 = new Book({
    title: 'JavaScript Patterns'
});

ok( book1.get('author') === 'Anonymous', 'Alapértelmezett értékű a szerző');

Initializing the model

var Book = Backbone.Model.extend({
    initialize: function () {
        console.log('Inicializálás')
    }
});

var book1 = new Book();

Copy of model data

var book1 = new Book({
    title: 'JavaScript Patterns',
    author: 'Stoyan Stefanov'
});
console.log(book1.toJSON());

Backbone.Collection

var Books = Backbone.Collection.extend({
    model: Book
});

Adding and removing models

add() and remove() method

var book1 = new Book({title: 'JavaScript Patterns'}),
    book2 = new Book({title: 'JavaScript: The Good Parts'}),
    book3 = new Book({title: 'Maintainable JavaScript'});

var books = new Books([book1, book2]);

books.add(book3);
books.add({title: 'Testable JavaScript'});

books.remove(book3);

Getting a model from a collection

get() method (the id or cid attribute as the parameter)

var model = books.get(1);

Collection as an observable object

add, remove, change, etc. events

books.on('add', function (book) {
    console.log(book);
})

Setting the whole collection

  • set()
  • reset()

Array functions

See underscore library

  • forEach()
  • filter()
  • min()/max()
  • find()
  • sortBy()
  • pluck()
  • etc.
//Collecting only the title attributes
var titles = books.pluck('title');
console.log(titles);

//Filtering
var filtered = books.filter(function (book) {
    return book.get('title').indexOf('Pa') > -1;
});
console.log(filtered);

Backbone.View

Creating and displaying a new view

var BookView = Backbone.View.extend({
    el: '#bookDiv',
    template: _template( $('#book-template').html() ),
    model: book1,

    initialize: function () {
        this.listenTo(this.model, 'change', this.render);
    },

    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
    }   
});

Event handling

var BookView = Backbone.View.extend({
    el: '#bookDiv',
    
    events: {
        'click #button': 'save',
        'keyup input': 'writing'
    },

    save: function (e) { /*...*/ },

    writing: function (e) { /*...*/ },
});

Backbone.Router

var BookRouter = Backbone.Router.extend({

    routes: {
        "about" : "showAbout",
        /* e.g. http://example.com/#about */

        "book/:id" : "getBook",
        /* e.g. http://example.com/#todo/5 */

    },

    showAbout: function(){
    },

    getBook: function(id){
        console.log("A keresett könyv: " + id);
    }
});

var bookRouter = new BookRouter();
Backbone.history.start();

Backbone and ECMAScript 2015

You can use ES6 language features wherever you want!

Guidelines

Backbone is not fully compatible with ES6 class strucure.

Use extend() instead!

var MyView = Backbone.View.extend({
    initialize() {
        /*...*/
    },
    someMethod() {
        /*...*/
    }
});

Practice

Try the concepts contained in the slides above! Use a JavaScript sandbox (e.g. jsfiddle or jsbin) for your experiments!

Check out the structure of the resulting objects!