Backbone: Set and Unset Model with Form

Backbone: Set and Unset Model with Form

by Nirvanachain

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<div class="js-form">
</div>
<div class="js-output">
</div>

<script type="text/template" id="form-template">
    <h1>Form</h1>
    <form action="" method="Post">
        <div>
            <label for="firstName">First Name:</label>
            <input type="text" class="js-input" id="firstName" name="f_Name" />
        </div>
        <div>
            <label for="lastName">Last Name:</label>
            <input type="text" class="js-input" id="lastName" name="l_Name" />
        </div>
    </form>
</script>

<script type="text/template" id="output-template">
    <div>
        f_Name = <%- settings.f_Name %>
        <br />
        l_Name = <%- settings.l_Name %>
    </div>
</script>

JavaScript

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

var theModel = new TheModel();

var TheFormView = Backbone.View.extend({
    el: '.js-form',
    
    initialize: function() {
        this.model = theModel; 
        
    },
    
    template: _.template( $('#form-template').html() ),
    
    render: function() {

        this.$el.html( this.template({settings: this.model.toJSON()}) );
        
        return this;
    },
    
    events: {
        'blur .js-input': 'updateModel'  
    },
    
    updateModel: function(e) {
        var name = e.target.name,
            value = e.target.value;
        
        if (value !== '') {
            this.model.set(name, value);
        }
        // Why does unset not get fired here? 
        else if ( this.model.has(name) ) {
            this.model.unset(name);   
        }
    }
    
});

var TheOutputView = Backbone.View.extend({
    el: '.js-output',
    
    initialize: function() {
        this.model = theModel;  
        
        this.listenTo(this.model, 'change', this.render);
    },
    
    template: _.template( $('#output-template').html() ),
    
    render: function() {

        this.$el.html( this.template({settings: this.model.toJSON()}) );
        
        return this;
    },
    
});

var theFormView = new TheFormView();
theFormView.render();

var theOutputView = new TheOutputView();
theOutputView.render();