2

我对 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"));
    })
}

该函数在页面加载时调用并像这样引用:

<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"));
        })
    }
4

1 回答 1

1

无需使用全局变量。您可以在视图模型中添加一个selectedTeamobservable,它代表所选选项:

var teamViewModel = {
    teams: ko.observableArray([]),
    selectedTeam: ko.observable(),
    // ...
}

然后,将 options' 绑定 valueselectedTeam,即:

<select data-bind="options: teams,  optionsText: 'name', value: selectedTeam">
</select>

最后,要访问id所选选项的 ,只需使用teamViewModel.selectedTeam().id

这是一个演示

于 2012-10-22T16:03:40.803 回答