我创建了我的第一个 KO 组件:
组件.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 的组件中选择的项目?