Skip to content

Instantly share code, notes, and snippets.

@knowtheory
Created June 13, 2014 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knowtheory/389e853c7e1d541e6a4a to your computer and use it in GitHub Desktop.
Save knowtheory/389e853c7e1d541e6a4a to your computer and use it in GitHub Desktop.
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.getElementById('tc-backbone'),
model: new Temperature(),
events: {
'input .celsius': 'updateCelsius',
'input .fahrenheit': 'updateFahrenheit'
},
initialize: function() {
this.listenTo(this.model, 'change:celsius', this.render);
this.render();
},
render: function() {
var celsius = this.$('.celsius');
var fahrenheit = this.$('.fahrenheit');
if (document.activeElement !== celsius[0] ) celsius.val(this.model.get('celsius'));
if (document.activeElement !== fahrenheit[0] ) fahrenheit.val(this.model.fahrenheit());
},
updateCelsius: function(event) {
this.model.set('celsius', event.target.value);
},
updateFahrenheit: function(event) {
this.model.fahrenheit(event.target.value);
}
});
new TemperatureView();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment