我在我的项目中使用了Backbone。但是当我尝试在视图上使用双向数据绑定时,当用户更改绑定文本字段时,我无法更新默认值。下面是我的示例代码:无法更新双向数据绑定的默认值
jQuery(document).ready(function($) {
var MyModel = Backbone.Model.extend({
defaults: {
"val_one": "1",
"val_two": "2"
}
});
var MyView = Backbone.View.extend({
initialize: function() {
var self = this;
this.model = this.model || new MyModel();
this.viewModel = {
val_one: ko.observable(this.model.get('val_one')),
val_two: ko.observable(this.model.get('val_two'))
}
this.viewModel.val_one.subscribe(function(newValue) {
self.model.set({val_one:newValue});
});
this.viewModel.val_two.subscribe(function(newValue) {
var nNumber = parseInt(newValue) + parseInt(self.model.get('val_one'));
self.model.set({val_two:nNumber});
});
this.model.on("change", function() {
console.log("Model changed");
//you can do whatever you want with your model now
//e.g sync it with the server, update parts of your
//view, etc
})
},
render: function() {
var that = this;
_.each(this.model.attributes, function(val, key) {
var row = "<tr><td><input type='text' data-bind='value: " + key + "' /></td><td><p data-bind='text: " + key + "'>0</p></td></tr>";
$('#mytable').append(row);
});
ko.applyBindings(this.viewModel);
}
});
function UpdateView(){
var newModel = new MyModel();
var modelView = new MyView({model: newModel});
modelView.render();
}
UpdateView();
});
我已经写了这行代码:var nNumber = parseInt(newValue) + parseInt(self.model.get('val_one'));
。所以无论何时用户更新文本字段,默认值都应该更新。但标签不会更新为新号码。
所以我想新的数字应该被替换在文本字段旁边的标签中。请看图片:
问候,
*“当我尝试在我的视图上使用双向数据绑定时”* - 请解释您是如何尝试实现这一点的。什么是'ko' ..?你可以创建一个[mcve],因为我们甚至不知道你正在使用什么库。 –