select onchange返回错误的值

时间:2012-10-22 20:25:23

标签: jquery jquery-mobile knockout.js

我有一个看起来像这样的modelView:

var teamViewModel = {
        teams: ko.observableArray([]),
        selectedTeam: ko.observable({id: 1}),
        clearTeams: function(){
            this.teams.removeAll();
        },
        addTeam: function (id, name, isChecked) {
            t = new team(id, name, isChecked);
            this.teams.push(t);
        }
    };

我在这里引用它:

<select id="teamNameLabel" date-theme="f" data-bind="options: teams, optionsText: 'id', value: selectedTeam"></select>

当我选择其中一个团队时,我可以点击按钮:

<input id="TestButton" type="button" onclick="GetAllUsersByTeam()" value="Show Selected Team" />

它会称之为:

function GetAllUsersByTeam(){

        var url = 'http://localhost/Service.svc/GetUsersByTeam/'+teamViewModel.selectedTeam().id;

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

这就像我想要它一样。但我想改变,以便在onchange上调用GetAllUsersByTeam()。但是:

<select id="teamNameLabel" date-theme="f" onchange="GetAllUsersByTeam()" data-bind="options: teams, optionsText: 'id', value: selectedTeam"></select>

总是迟到1个ID。例如,当我选择1时,id为1,2 id为1,3 id为2 ... 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

为什么不在您的模型中订阅selectedTeam

this.selectedTeam.subscribe(function(newValue) {
    GetAllUsersByTeam();
});