Backbone.js的:避免视图→模型→查看双转换 [英] Backbone.js: avoid view→model→view double conversion
问题描述
我试图建立这样的:结果
当我在编辑栏的左侧应该更新一个在右边,反之亦然。
When I edit field on the left it should update the one on the right and vice-versa.
-
在输入字段编辑值导致文本光标在它的结束跳。
Editing a value in an input field causes the text cursor to jump at the end of it.
在华氏字段中输入2获取与1.999999999999取代,因为你可以在截图中看到。这是因为双转换的:搜索
视图Fº→模型→Cº视图的Fº。
Typing "2" in the fahrenheit field gets replaced with 1.999999999999, as you can see on the screenshot. This happens because of the double conversion:
view’s Fº → model’s Cº → view’s Fº.
我怎样才能避免呢?
更新:
我想知道处理的MVC框架的双向绑定,如Backbone.js的优雅的方式。
I want to know the elegant way of dealing with two-way bindings in MVC frameworks such as Backbone.js.
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);
}
它不仅解决了这个问题,它也降低了code3.5⨉。显然,我在做MVC错误的。
Not only it fixes the problem, it’s also reduces the code 3.5⨉. Clearly I’m doing MVC wrong.
推荐答案
下面是我拿到这个;而不是呈现在每一个变化的全貌,在交互视图,请使用视图的jQuery的或纯JS上下文就像你的非MVC例子。
Here's my take on this; instead rendering the whole view on every change, in interactive views, use the view's jQuery or plain JS contexts just like your non-MVC example.
http://jsbin.com/fomugixe/1/edit
为骨干文档说:
双向数据绑定是可以避免的。虽然它肯定使一个漂亮的演示,并适用于最基础的CRUD,它不容易在你的现实世界的应用程序非常有用。有时你要更新每一个关键preSS,有时模糊,有时当面板闭合,有时当保存按钮被点击。
"Two way data-binding" is avoided. While it certainly makes for a nifty demo, and works for the most basic CRUD, it doesn't tend to be terribly useful in your real-world app. Sometimes you want to update on every keypress, sometimes on blur, sometimes when the panel is closed, and sometimes when the "save" button is clicked.
这篇关于Backbone.js的:避免视图→模型→查看双转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!