在视图模型中访问 KO 组件字段

Accessing KO component fields in viewmodel

我已经创建了我的第一个 KO 组件:

components.js

ko.components.register('team-dropdown', {
    viewModel: function (params) {

        var self = this;
        self.teamNames = ko.observableArray([]);

        $.ajax({
                url: 'http://footballcomps.cloudapp.net/Teams',
                type: 'get',
                contentType: 'application/json',
                success: function (data) {
                    $.each(data['value'], function (key, value) {
                        self.teamNames.push(value.TeamName);
                    });
                    console.dir(self.teamNames);
                },
                error: function (err) {
                    console.log(err);
                }
            });

        self.selectedTeam = ko.observable();
    },
    template: { require: 'text!components/team-dropdown.html' }
});

团队-dropdown.html

<div id="teams" class="inputBlock form-group">
<select class="form-control" name="teamName" data-bind="options: teamNames, value:selectedTeam"></select>
<label id="lblHomeTeam" data-bind="text: selectedTeam"></label>

这是我想在其中使用该组件的视图:

<div class="row" id="divFixture">
<div class="col-md-4">
    <div class="panel panel-info">
        <div class="panel-heading">
            <h2 class="panel-title">Add new fixture</h2>
        </div>
        <div class="panel-body">

            <form data-bind="submit: fixture.addFixture">
                <div class="form-group">
                    <team-dropdown />
                </div>....
            </form>

还有我精简的视图模型:

define(['knockout', 'knockout.validation', 'common', 'components'], function (ko) {

    return function fixtureViewModel() {

        function fixture(fixtureId, fixtureDate, homeId, homeName, homeBadge, homeScore, awayId, awayName, awayBadge, awayScore) {
            this.FixtureId = fixtureId;
            this.FixtureDate = fixtureDate;
            this.HomeId = homeId;
            this.HomeName = homeName;
            this.HomeBadge = homeBadge;
            this.HomeScore = homeScore;
            this.AwayId = awayId;
            this.AwayName = awayName;
            this.AwayBadge = awayBadge;
            this.AwayScore = awayScore;
        }

        var self = this;

        self.Id = ko.observable();
        self.FixtureDate = ko.observable();
        self.HomeId = ko.observable();
        self.HomeName = ko.observable();
        self.HomeBadge = ko.observable();
        self.HomeScore = ko.observable();
        self.AwayId = ko.observable();
        self.AwayName = ko.observable();
        self.AwayBadge = ko.observable();
        self.AwayScore = ko.observable();

        self.selectedTeam = ko.observable();

        self.addFixture = function() {

            //how do I reference the selected item from my component here?

    };     
});

如何在 self.addFixture 中引用我在我的组件中选择的项目?

由于 team-dropdown 是一个可重复使用的组件,您应该提供一种绑定到它的方法。正如您所拥有的,它是一个独立的控件,外部世界无法与它交互,除非通过您定义的可观察对象,这不会使其非常灵活。

我会向它添加参数,您可以在其中设置要绑定到值的可观察对象。您的固定装置有一个 selectedTeam 属性,所以这似乎是一个可能的候选者。

ko.components.register('team-dropdown', {
    viewModel: function (params) {
        var self = this,
            teamNames = ko.observableArray([]),
            // default to a local observable if value not provided
            selectedTeam = params.value || ko.observable();

        // you probably don't want others to directly modify the teamNames array
        self.teamNames = ko.pureComputed(teamNames);
        self.selectedTeam = selectedTeam;

        $.ajax({
            url: 'http://footballcomps.cloudapp.net/Teams',
            type: 'get',
            contentType: 'application/json',
            success: function (data) {
                $.each(data['value'], function (key, value) {
                    // push to the local `teamNames` array
                    teamNames.push(value.TeamName);
                });
                console.dir(teamNames);
            },
            error: function (err) {
                console.log(err);
            }
        });
    },
    template: { require: 'text!components/team-dropdown.html' }
});

然后在使用组件时设置参数:

<form data-bind="submit: fixture.addFixture">
    <div class="form-group">
        <team-dropdown params="value: fixture.selectedTeam" />
    </div>
</form>

所选值现在应该设置在您的夹具的 selectedTeam 中,因此您可以直接使用它。

self.addFixture = function() {
    var selectedTeam = self.selectedTeam(); // should have the value
};