Created
June 13, 2014 13:13
-
-
Save knowtheory/389e853c7e1d541e6a4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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