我有以下客户端代码:

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());

08-19 01:06