鉴于此页面上给我的优雅示例: knockout.js - modify DOM in current item in list (expand list item subsection) using templates
我想在每个工作中添加一个名为“JobNotes”的子项目列表。假设现在 JobNote 具有“Id”和“Text”的结构。我将如何在我的工作列表中对子项目列表进行数据绑定?
谢谢。
鉴于此页面上给我的优雅示例: knockout.js - modify DOM in current item in list (expand list item subsection) using templates
我想在每个工作中添加一个名为“JobNotes”的子项目列表。假设现在 JobNote 具有“Id”和“Text”的结构。我将如何在我的工作列表中对子项目列表进行数据绑定?
谢谢。
这个问题的答案可以在这个 jsFiddle 上找到
<div data-bind="foreach: jobs">
<div>
<div class="jobContainer">
<label data-bind="text: data.JobTitle"></label>
<l`enter code here`abel data-bind="text: data.CompanyName"></label>
<div class="jobDetails" data-bind="visible: expanded">
<label data-bind="text: data.CityName"></label>
<label data-bind="text: data.JobIndustry"></label>
<div data-bind="foreach: notes">
<label data-bind="text: text"></label>
<a href="#" data-bind="click: $parent.deleteNote ">Remove</a>
</div>
</div>
<div>
<a href="#" data-bind="click: $parent.toggle, text: linkLabel">Expand</a>
<a href="#" data-bind="click: $parent.addNote">Add Note</a>
</div>
</div>
var json = [
{
"JobTitle": "Investment Banking Associate",
"CompanyName": "Value Line Consulting",
"CityName": "Sydney - Australia",
"JobIndustry": "Consulting - General",
"JobNotes": [
{
"Id": 4,
"JobId": 1474,
"Text": "A test Note!"}
],
"Id": 1474}
]
function JobNote(data) {
this.text= data.Text;
}
function Job(data) {
var self = this;
this.data = data;
this.notes = ko.observableArray([]);
// new JobNote("note1"),
// new JobNote("note2"),
// ]);
var mappedNotes = $.map(data.JobNotes, function(item) { return new JobNote(item) });
this.notes(mappedNotes);
this.someValue = ko.observable().extend({
defaultIfNull: "some default"
});
this.expanded = ko.observable(false);
this.linkLabel = ko.computed(function() {
return this.expanded() ? "collapse" : "expand";
}, this);
this.deleteNote = function(jobNote) {
self.notes.remove(jobNote);
}
};
var viewModel = function() {
var self = this;
this.jobs = ko.observableArray([
// new Job(json),
// new Job(),
// new Job(),
]);
this.toggle = function(item) {
item.expanded(!item.expanded());
}
this.addNote = function(job) {
job.notes.push(new JobNote("new note"));
}
var mappedJobs = $.map(json, function(item) {
return new Job(item)
});`enter code here`
self.jobs(mappedJobs);
};
ko.applyBindings(new viewModel());