Backbone Template

Standard fiddle

by paulyoder

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<html>
    <head>
  <body>
      <div id="sumForm">
          <input id="value1" type="text" /> +
          <input id="value2" type="text" /> =
          <input id="sum" type="text" />
      </div>
  </body>
</html>

JavaScript

SumModel = Backbone.Model.extend({
    initialize: function() {
        this.bind('change:value1', this.calculateSum, this);
        this.bind('change:value2', this.calculateSum, this);
    },
    
    defaults: {
        value1: 2,
        value2: 2,
        sum: 4
    },
    
    calculateSum: function() {
        var value1 = Number(this.get('value1') || '0');
        var value2 = Number(this.get('value2') || '0');
        this.set({ sum: (value1 + value2) });
    }
});

SumView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'bindElementChanges');
        this.model.bind('change:sum', this.onSumChange, this);
    },
    
    el: '#sumForm',
    
    bindElementChanges: function() {
        var self = this;
        $('#value1').keydown(function(e) {
            self.model.set({ value1: $(e.currentTarget).val() });
        });
    },
    
    onSumChange: function() {
        this.$('#sum').val(this.model.get('sum'));   
    }
});

$(function() {
    var sumModel = new SumModel();
    var view = new SumView({ model: sumModel });
});