Backbone

by Neviton

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<div class="form">
    <form action="">
        <input type="text" id="name" placeholder="Name" />
        <input type="text" id="sport" placeholder="Sport" />
        <input type="button" id="add" value="ADD" />
    </form>
</div>
<div id="data"></div>

CSS

body {
    font: 1em Arial,sans-serif;
    color: #440;
    background-color: #440;
}
.form {
    background-color: #fff;
    border-radius: 4px;
}

.form input {
    margin: 5px;
    padding: 5px;
    border-radius: 4px;
    border: 1px solid #ddd;
}

#data ul {
    padding: 0;
}
#data ul li {
    background-color: #aa7;
    list-style: none;
    padding: 10px;
    margin: 1px 0;
    border-radius: 4px;
}

JavaScript

var Model = Backbone.Model.extend({
    initialize: function() {
        this.on('change', this.onChange, this);
    },
    
    onChange: function(model) {
        console.log('Changed from ', this.previous('name'), ' to ', model.get('name'));
    }
});

var Collection = Backbone.Collection.extend({
    model: Model,
    url: "http://www.mocky.io/v2/540f163f89546f3e03a33c7c",
    
    initialize: function() {
        this.on('add', this.onAdd);
    },
    
    onAdd: function(model) {
        console.log('Added: ', model.get('name'));
    }
});

var FormView = Backbone.View.extend({
    model: new Model(),
    el: 'form',
    events : {
        'click #add': 'addModel',
        'change input': 'updateModel'
    },
    initialize: function() {
        this.listenTo(this.model, 'change', this.updateFields);
    },

    updateModel: function() {
        this.model.set({
            name: this.$el.find('#name').val(),
            sport: this.$el.find('#sport').val()
        });
        console.log(this.model.toJSON());
    },
    
    updateFields: function(model) {
        this.$el.find('#name').val(model.get('name'));
        this.$el.find('#sport').val(model.get('sport'));
    },
    
    addModel: function() {
        this.trigger('itemAdded');
    }
});

var ItemView = Backbone.View.extend({
    tagName: 'li',
    
    events : {
        'click li': 'itemEdit'
    },
    
    render: function() {
        this.$el.html(_.values(this.model.toJSON()).join(' - '));
        return this;
    }
});

var MainView = Backbone.View.extend({
    tagName: 'ul',
    events: {
        'click li':'edit'
    },
    initialize: function() {
        this.collection = new Collection();
        this.formView = new FormView();
       
        this.listenTo(this.collection, 'add', this.addModel);
        this.listenTo(this.formView, 'itemAdded', this.addItem);
        
        this.collection.fetch();
    },
    addItem: function() {
        this.collection.add({
            name:...