knockout.js - 添加/删除模型子列表中的项目

时间:2012-05-15 13:59:39

标签: model-view-controller foreach knockout.js ko.observablearray

我有一个foreach模板,显示页面上的作业列表。在每份工作中,我都有一份工作说明清单。我无法设置正确的observable以允许在视图中更新作业注释。

以下是jsFiddle的链接:http://jsfiddle.net/b3B8p/

或者,这是代码。我不确定是将子列表的可观察数组放入Job对象本身还是放入View ...

<div data-bind="foreach: jobs">
    <div>
        <div class="jobContainer">
            <label data-bind="text: JobTitle"></label> 
            <label data-bind="text: CompanyName"></label>
            <div class="jobDetails" data-bind="visible: expanded">
                <label data-bind="text: City"></label>
                <label data-bind="text: State"></label>
                <div data-bind="foreach: Notes">
                    <label data-bind="text: Text"></label>               
                </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>    


function JobNote() {
    this.Text = "some text!";       
}

function Job() {
    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");
    this.Notes = ko.observableArray([
       new JobNote(),
       new JobNote(),       
    ]);

    this.someValue = ko.observable().extend({ defaultIfNull: "some default" });

    this.expanded = ko.observable(false);

    this.linkLabel = ko.computed(function () {
        return this.expanded() ? "collapse" : "expand";
    }, this);      
};

var viewModel = function () {
    this.jobs= ko.observableArray([
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),
        new Job(),        
        new Job(),
    ]);

    this.toggle = function (item) {
        item.expanded(!item.expanded());
    }

    this.addNote = function(job) {
         // what should go in here?
    }    
};

ko.applyBindings(new viewModel());​

1 个答案:

答案 0 :(得分:1)

正如Niko在这种情况下所说,我会将该方法添加到课程中。像这样。

function Job() {
    var self = this;

    this.JobTitle = ko.observable("some job");
    this.CompanyName = ko.observable("some company");
    this.City = ko.observable("some city");
    this.State = ko.observable("some state");

    this.Notes = ko.observableArray([
       new JobNote(),
       new JobNote(),       
    ]);

    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.toggle = function () {
        self.expanded(!self.expanded());
    };

    this.addNote = function () {
        self.Notes.push(new JobNote());
    }    
};

这可以保持一切美观和封装。

希望这有帮助。