我在我的項目中使用了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],因爲我們甚至不知道你正在使用什麼庫。 –