我刚刚开始了一个项目,我正在尝试将knockout用于我的viewmodel绑定。但我有一个问题,我无法让视图模型对选择框视图中的更改(通过手动订阅)作出反应。
var viewModel = function() {
var self = this;
self.project = ko.observable();
self.contractBorders = ko.observable();
self.contractBorders.subscribe(function (newvalue) {
alert('something changed!');
});
};
viewModel.load = function() {
var data = {"project":{"name":"Project XYZ",
"number":338,"id":1,"isNew":false},"contractBorders":[{"name":"Border 1 grund","id":1},
{"name":"Border 2","id":2},{"name":"Border 3","id":3}]}
viewModel.loadView(data);
};
viewModel.loadView = function(data) {
self.project = ko.mapping.fromJS(data.project);
self.contractBorders = ko.mapping.fromJS(data.contractBorders);
ko.applyBindings(viewModel);
};
viewModel.load();
我期待执行“self.contractBorders.subscribe”,但它永远不会发生。我完全错了吗?
我创建了一个小提琴来重现问题here
任何帮助将不胜感激!
/ BR Vinblad
答案 0 :(得分:1)
你在绑定和viewModel中有很多小错误 1)
viewModel.loadView = function(data) {
viewModel.project = ko.mapping.fromJS(data.project);
viewModel.contractBorders = ko.mapping.fromJS(data.contractBorders);
ko.applyBindings(viewModel);
};
2)
var viewModel = new function() {
3)
<div class="span2">
<select
4)
<input type="text" id="name" name="name" data-bind="value: project().name" />
这里我添加了可观察值 - selectedBorder
http://jsfiddle.net/6zzSy/24/
这里我优化你的代码
http://jsfiddle.net/6zzSy/25/