Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>Backbone two-ways bindings</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/zepto/1.0/zepto.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
</head>
<body>
  <input type=number id=celsius>
  <input type=number id=fahrenheit>
</body>
</html>
 
var Temperature = Backbone.Model.extend({
    defaults: {
        celsius: 0
    },
    fahrenheit: function(value) {
        if (typeof value == 'undefined') {
            return this.c2f(this.get('celsius'));
        }
        value = parseFloat(value);
        this.set('celsius', this.f2c(value));
    },
    c2f: function(c) {
        return 9/5 * c + 32;
    },
    f2c: function(f) {
        return 5/9 * (f - 32);
    }
});
var TemperatureView = Backbone.View.extend({
    el: document.body,
    model: new Temperature(),
    events: {
        "input #celsius": "updateCelsius",
        "input #fahrenheit": "updateFahrenheit"
    },
    initialize: function() {
        this.listenTo(this.model, 'change:celsius', this.render);
        this.render();
    },
    render: function() {
        this.$('#celsius').val(this.model.get('celsius'));
        this.$('#fahrenheit').val(this.model.fahrenheit());
    },
    updateCelsius: function(event) {
        this.model.set('celsius', event.target.value);
    },
    updateFahrenheit: function(event) {
        this.model.fahrenheit(event.target.value);
    }
});
var temperatureView = new TemperatureView();
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
NVpro
0viewers