knockout.js - 列表中的数据绑定子项

时间:2012-05-15 04:02:36

标签: dom data-binding knockout.js

鉴于此页面上给我的优雅例子: knockout.js - modify DOM in current item in list (expand list item subsection) using templates

我想在每个作业中添加一个名为“JobNotes”的子项列表。现在让我们说JobNote的结构为“Id”和“Text”。我如何在我的工作列表中数据化子项目列表?

感谢。

1 个答案:

答案 0 :(得分:1)

这个问题的答案可以在这个jsFiddle上找到

http://jsfiddle.net/R4Gnw/21/

<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());​