【发布时间】:2013-04-05 02:25:01
【问题描述】:
我正在尝试构建this:
当我编辑左侧的字段时,它应该更新右侧的字段,反之亦然。
在输入字段中编辑值会导致文本光标跳到它的末尾。
如屏幕截图所示,在华氏温度字段中键入“2”将替换为 1.999999999999。这是因为双重转换:
视图的 Fº → 模型的 Cº → 视图的 Fº。
我怎样才能避免这种情况?
更新:
我想知道在 MVC 框架(例如 Backbone.js)中处理双向绑定的优雅方式。
MVC
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();
没有 MVC
celsius.oninput = function(e) {
fahrenheit.value = c2f(e.target.value)
}
fahrenheit.oninput = function(e) {
celsius.value = f2c(e.target.value)
}
function c2f(c) {
return 9/5 * parseFloat(c) + 32;
}
function f2c(f) {
return 5/9 * (f - 32);
}
不仅解决了问题,还减少了代码 3.5⨉。显然我做错了 MVC。
【问题讨论】:
-
我通常乘以生成非小数整数所需的任何因子 10,进行数学运算,然后在完成后除以因子 10,以避免 javascript 十进制数学的粗俗。
标签: model-view-controller data-binding backbone.js model-binding