我有以下客户端代码:
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]
。 最佳答案
请检查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());