我在项目中使用了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'));
。因此,每当用户更新文本字段时,默认值都应该更新。但标签没有更新新号码。
所以我想在文本字段旁边的标签中替换新号码。请看图片:
此致
答案 0 :(得分:1)
这是一个为双向绑定创建的简单EventManager。随意使用它。
define(['underscore','backbone'], function (_, Backbone) {
"use strict";
var EventManager,
wrapperCallback,
triggerParams,
receiverName,
senderObj;
EventManager = function () {
this.bind = function (sender, receiver, eventName, callback, clearAll, senderName) {
wrapperCallback = this.getWrapperCallback(receiver, eventName, senderName, callback);
if (clearAll === true) {
sender.unbind(eventName);
} else {
sender.unbind(eventName, wrapperCallback);
}
console.log("Bind " + receiverName + " on " + senderName + "." + eventName);
sender.bind(eventName, wrapperCallback, receiver);
};
this.trigger = function (sender, eventName, data) {
console.log("Trigger Event: " + eventName);
senderObj = sender;
[].splice.call(arguments, 0, 1);
senderObj.trigger.apply(senderObj, arguments);
};
this.getWrapperCallback = function (receiver, eventName, senderName, callback) {
function wrapperFunction(params) {
console.log("Received Event: " + eventName + " from " + senderName);
callback.apply(receiver, arguments);
}
return wrapperFunction;
};
};
return new EventManager();
});
答案 1 :(得分:0)
BackboneJs没有双向数据绑定,你需要通过使用事件监听器自己实现它,在你的情况下使用onkeyup事件监听器来连接视图和模型