我有以下客户端代码:
var ProfileManager = function () {
self.SelectedLanguage = ko.observable();
self.SelectedLanguage.subscribe(function (newValue) {
alert("The person's new name is " + newValue);
});
var bindUIwithViewModel = function (viewModel) {
ko.applyBindings(viewModel);
};
}
我后来做bindUIwithViewModel(self);
。
和绑定到SelectedLanguage
的HTML选择:
<select id="selectAvailableLanguages" class="form-control language-select" data-bind="options: AvailableLanguages, optionsText: 'Code', value : SelectedLanguage"></select>
成功填充了select
,SelectedLanguage
可观察内的值发生了变化,但alert
刚刚赢了。有什么想法吗?
另外,不知道是否相关,但observe
内的__ko.mapping_
数组是array[0]
..
答案 0 :(得分:0)
请检查fiddle。注意,“AvailableLanguages”和“SelectedLanguage”属性应存在于同一上下文中,即属于绑定视图模型。
我修改了你的JS代码:
var ProfileManager = function () {
self.SelectedLanguage = ko.observable();
self.SelectedLanguage.subscribe(function (newValue) {
alert("The person's new name is " + JSON.stringify(newValue));
});
self.AvailableLanguages = [ { Code: 'c++', Person: 'John' }, { Code: 'c#', Person: 'Mark' } ]
}
ko.applyBindings(new ProfileManager());