我非常了解Knockoutjs,我正在尝试在输入选择上执行服务调用。
我的对象看起来像这样:
var teamViewModel = {
teams: ko.observableArray([]),
clearTeams: function(){
this.teams.removeAll();
},
addTeam: function (id, name, isChecked) {
t = new team(id, name, isChecked);
this.teams.push(t);
}
};
通过调用以下内容填充选择框:
function GetAvailableTeams() {
var jqxhr =
$.getJSON('http://localhost/Service.svc/GetTeamsAll',
function (data) {
teamViewModel.clearTeams();
$.each(data.GetTeamsAllResult,
function (key, val) {
teamViewModel.addTeam(val.TeamId, val.TeamName, true);
});
ko.applyBindings(teamViewModel, document.getElementById("teamNameLabel"));
})
}
该函数在pageload上调用,并按如下方式引用:
<select id="teamNameLabel" date-theme="f" data-bind="options: teams, optionsText: 'name', value: 'id'"></select>
如果选择select语句上的选项,如何更新全局变量TeamId?
编辑:
function GetAllUsersByTeam(){
var url = 'http://localhost/Service.svc/GetUsersByTeam/'+TeamId;
var jqxhr =
$.getJSON(url,
function (data)
{
colleagueViewModel.clearColleagues();
$.each(data.GetUsersByTeamResult, function (key, val) {
colleagueViewModel.addColleague(val.FirstName, val.LastName, val.EmailAddress, val.PhoneNumber, val.LocationName, val.CapabilityId, val.CoeId);
});
ko.applyBindings(colleagueViewModel, document.getElementById("colleaguesListView"));
})
}
答案 0 :(得分:1)
无需使用全局变量。您可以向视图模型添加selectedTeam
observable,它代表所选的选项:
var teamViewModel = {
teams: ko.observableArray([]),
selectedTeam: ko.observable(),
// ...
}
然后,bind the options' value
到selectedTeam
,即:
<select data-bind="options: teams, optionsText: 'name', value: selectedTeam">
</select>
最后,要访问所选选项的id
,只需使用teamViewModel.selectedTeam().id
。
这是 DEMO 。